Accepted Java solution in O(n).


  • 0
    C

    '''
    public class Solution {
    public boolean isNumber(String s) {
    int dotCount=0,eCount=0;
    s=s.trim();
    boolean parentE=false;
    boolean parentDot=false;

        if(s.length()==0)
            return false;
        for(int i=0;i<s.length();i++){
            if((s.charAt(i)=='-'||s.charAt(i)=='+') && i==0)
                continue;
            if(s.charAt(i)>='0' && s.charAt(i)<='9'){
                if(eCount==0){
                    parentE=true;
                }
                if(dotCount==0)
                    parentDot=true;
                continue;
            }
                
            else
                if(s.charAt(i)=='.'){
                    if(dotCount>0)
                        return false;
                    dotCount++;
                    if(eCount>0
                    ||(i>0 && (s.charAt(i-1)<'0' || s.charAt(i-1)>'9') && (s.charAt(i-1)!='-' && s.charAt(i-1)!='+')) 
                    || (i==s.length()-1 && !parentDot)
                    ||(i+1<s.length() && s.charAt(i+1)!='e' && (s.charAt(i+1)<'0' || s.charAt(i+1)>'9')))
                        return false;
                }
            else
                if(s.charAt(i)=='e'){
                    if(eCount>0)
                        return false;
                    eCount++;
                    if(i==0
                    ||!parentE
                    ||( s.charAt(i-1)!='.' && (s.charAt(i-1)<'0' || s.charAt(i-1)>'9'))
                    || i==s.length()-1
                    ||(!(s.charAt(i+1)>='0' && s.charAt(i+1)<='9')) && s.charAt(i+1)!='+' && s.charAt(i+1)!='-')
                        return false;
                }
            else
                if(s.charAt(i)=='+' || s.charAt(i)=='-'){
                    if(i==s.length()-1||
                    s.charAt(i-1)!='e')
                        return false;
                }
            
            else
            return false;
        }
        
        return true;
    }
    

    }
    '''


Log in to reply
 

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