Items discussed more
Examples of the first to observe, as well as the title character in answer to the prompt that can be included --valid
Find:
"+ -" either at the beginning or followed by e, only these two positions
"E", before and after must have a number, and not appeared before e
".", Appeared in front of e or not. ""
So we can use several flag
There have been digital representation before seenNum
E represents digital After seenNumAfterE
dot represents the appearance before too. ""
E represents occurred before e
Note that initialization of seenNumAfterE = true, because not necessarily contain e s, e again appears like it to false. Other flag are set to false
Finally, return seenNum && seenNumAfterE
1 class Solution { 2 public boolean isNumber(String s) { 3 boolean seenNum = false, seenNumAfterE = true; 4 boolean dot = false, e = false; 5 s = s.trim(); //去掉首尾的空格 6 int count = 0; 7 for(char i : s.toCharArray()){ 8 if(i >= '0' && i <= '9'){ 9 seenNum = true; 10 seenNumAfterE = true; 11 }else if(i == '.'){ 12 if(e || dot) 13 return false; 14 dot = true; 15 }else if(i == 'e'){ 16 if(e || !seenNum) 17 return false; 18 seenNumAfterE = false; 19 e = true; 20 }else if(i == '+' || i == '-'){ 21 if(count != 0 && s.charAt(count - 1) != 'e') 22 return false; 23 }else 24 return false; 25 26 count++; 27 } 28 29 return seenNum && seenNumAfterE; 30 } 31 }