my solution by using regular expression


  • 0
    P

    when string contains 'e', the string must contains only one 'e'. And the left part is a legal number include float and integer, the right part is a legal integer include positive and negative integer.

    class Solution {
        public boolean isNumber(String s) {
            if (s == null)
                return false;
            boolean isNum = false;
            String regx0 = "[+-]?[0-9]+";  //legal integer
            String regx1 = "[+-]?\\.[0-9]+"; // legal float 1
            String regx2 = "[+-]?[0-9]+\\.[0-9]*"; //legal float 2
    
            String str = s.trim();
            String subStr[];
            if (str.contains("e")) {
                if(str.matches(".*e.*e.*")) //str must contains only one 'e'
                    return false;
                subStr = str.split("e");
                if (subStr.length != 2)
                    isNum = false;
                else{
                    if ((subStr[0].matches(regx0) || subStr[0].matches(regx1) || subStr[0].matches(regx2)) && (subStr[1].matches(regx0)))
                        isNum = true;
                    else isNum = false;
                }
            } else {
                if (str.matches(regx0) || str.matches(regx1) || str.matches(regx2))
                    isNum = true;
                else
                    isNum = false;
            }
            return isNum;
        }
    }
    

Log in to reply
 

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