2015年9月24日星期四

Leetcode 65 Valid Number

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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.
Solution 1: very difficult to go over all the corner case, think hard about below code. The process is: iterate through the string, ignore blanks at the start, ignore plus or minus sign. check next substring with nums and dot only is valid. Then could appear 'e' follow by another valid number which might with plus/minus sign. Last, ignore blanks to the end. If we are not in the end. return flase.
 public class Solution {  
   public boolean isNumber(String s) {  
     int n=s.length();  
     int i=0;  
     while (i<n && s.charAt(i)==' ') i++;  
     if (i==n) return false;  
     if (s.charAt(i)=='+' || s.charAt(i)=='-') i++;  
     int dot=0, num=0;  
     while (i<n) {  
       if (s.charAt(i)=='.') {dot++; i++;}  
       else if (s.charAt(i)>='0' && s.charAt(i)<='9') {num++; i++;}  
       else break;  
     }  
     if (dot>1 || num==0) return false;  
     if (i<n && s.charAt(i)=='e') {  
       i++;  
       if (i==n) return false;  
       if (s.charAt(i)=='+' || s.charAt(i)=='-') i++;  
       int r=i;  
       while (i<n) {  
         if (s.charAt(i)>='0' && s.charAt(i)<='9') {num++; i++;}  
         else break;  
       }  
       if (i==r) return false;//must have one digit of number  
     }  
     while (i<n && s.charAt(i)==' ') i++;  
     return i==n;  
   }  
 }  

没有评论:

发表评论