Share my Solution using String split


  • 0
    Y

    My Idea is to use String.split to separate the string into parts and test the validity of each part.


    public class Solution {
    public boolean isNumber(String s) {
        if(s==null)
            return false;
        s=s.trim().toUpperCase(); // remove leading and trailing whitespaces.
        int n=s.length();
        String[] tokens=s.split("[E]",-1); // limiter -1 preserves all the tokens including leading and trailing ""
        if(tokens.length!=1 && tokens.length!=2) // s is "" or has at least two 'E', invalid
            return false; 
        if(tokens.length==1)
            return checkFloat(tokens[0]); // has no 'E', then check whether is a pure float.
        return checkFloat(tokens[0]) && checkSeriesNum(true,false,tokens[1]);
    }
    
    private boolean checkFloat(String s){
        String[] tokens=s.split("[.]",-1);
        if(tokens.length!=1 && tokens.length!=2)
            return false;   // empty string or have more than one '.'
        if(tokens.length==1)  // an Integer
            return checkSeriesNum(true,false,tokens[0]); // can have sign, but not alone.
        if(tokens[0].length()==0) // '.' at start, '.xxx'
            return checkSeriesNum(false,false,tokens[1]);
        if(tokens[1].length()==0) // '.' at end, 'xxx.' 
            return checkSeriesNum(true,false,tokens[0]); // cannot be only sign
        return checkSeriesNum(true,true,tokens[0]) && checkSeriesNum(false,false,tokens[1]);
    }       
    
    private boolean checkSeriesNum(boolean canHaveSign, boolean onlysign, String s){
        int n=s.length();
        char[] schar=s.toCharArray();
        if(n==0)
            return false;
        if(n==1){
            if(canHaveSign && onlysign)
                return (schar[0]>='0' && schar[0]<='9') || schar[0]=='+' || schar[0]=='-';
            return schar[0]>='0' && schar[0]<='9';
        }
        int i=0;
        while(i<n){
            if(i==0 && canHaveSign && (schar[i]=='+' || schar[i]=='-')){
                i++;
                continue;
            }
            if(schar[i]<'0' || schar[i]>'9')
                return false;
            i++;
        }
        return true;
    }
    

    }


  • 0
    S

    Pay attention to "Writing code? Select a code block and click on the button to preserve code formatting.” above text editor.


Log in to reply
 

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