Why not use regular expression in java?


  • 1
    A

    OJ is unfair, because for java, regular expression cannot be used directly. If we make use of regular expression, this problem will become extremely simple:

    public class Solution {
        public int atoi(String str) {
            if (str == null) {
                return 0;
            }
            
            // a named group is used here: number
            java.util.regex.Pattern p = java.util.regex.Pattern.compile("^\\s*(?<number>[\\+-]?\\d+).*$");
            java.util.regex.Matcher m = p.matcher(str);
            
            if (m.find()) {
                String numberStr = m.group("number");
                char signChar = numberStr.charAt(0);
                
                if (signChar >= '0' && signChar <= '9') {
                    signChar = '+';
                }
                
                int number = -1;
                try {
                    number = Integer.parseInt(numberStr);
                } catch (Exception e) {
                    if (signChar == '-') {
                        number = Integer.MIN_VALUE;
                    } else {
                        number = Integer.MAX_VALUE;
                    }
                }
                
                return number;
                
            }
            
            return 0;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.