Sunday, March 8, 2015

65. Valid Number Leetcode Java

Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Solution:
The key point of this problem is that we have to gather all possible cases, the problem is intended to be ambiguous. This problem is to test whether you have a comprehensive knowledge about a valid number. 
Basically, we have to find what kind of number is not valid.
After trim the string: remove all the leading space and trailing space
First of all, if there is a sign '+' or '-', it must be the first char or after a 'e' or 'E' and must be followed by number.
Secondly, if there is a 'e' or 'E', there must be no 'e' or 'E' occurred before, which means, only one scientific sign is allowed. There must be numbers before it and after it.
Thirdly, if there is a '.', must be no scientific sign before it and no dot before it. It must either follow a number or be followed by a number or scientific sign. 
Fourthly, no other character is allowed 
 public boolean isNumber(String s) {  
    String ss=s.trim();  
    if(ss==null || ss.length()==0) return false;  
    boolean eflag=false;  
    boolean dflag=false;  
    boolean nflag=false;  
    for(int i=0;i<ss.length();i++){  
      if(ss.charAt(i)=='+' || ss.charAt(i)=='-') {  
        if(i==0 || ss.charAt(i-1)=='E' || ss.charAt(i-1)=='e'   
        && (i<ss.length()-1 && ss.charAt(i+1)>='0' && ss.charAt(i+1)<='9')) continue;  
        else return false;  
      }  
      else if(ss.charAt(i)=='E'||ss.charAt(i)=='e'){  
        if(!nflag || eflag || i==ss.length()-1) return false;  
        eflag=true;  
      }  
      else if(ss.charAt(i)=='.'){  
        if(eflag || dflag || (!nflag&& i==ss.length()-1)) return false;  
        dflag=true;  
      }  
      else if(ss.charAt(i)<='9' && ss.charAt(i)>='0') nflag=true;  
      else return false;  
    }  
    return true;  
   }  

No comments:

Post a Comment