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.
一刷
题解:用deterministic finite automaton图来解决状态转移的问题。
- 我们先对s进行trim操作,去除头尾的空格space
- 设置一个变量hasNum来判断在string中是否曾经出现过数字,这个对于判断state 6的dot很关键
- 从0开始遍历string,根据state machine写code,假设c为当前字符,我们考虑以下情况
- 当c为数字
- 当c为'+'或者'-'
- 当c为'.'
- 当c为'e', 这时要注意从s6到s3这条, 这里的条件为 state = s6 && hasNum,这样才可以进入s3
- 其他返回false
- 最后判断state是否在2, 5, 7以及 (state == 6 && hasNum)
Time Complexity - O(n),Space Complexity - O(1)
public class Solution {
public boolean isNumber(String s) {
if(s == null || s.length() == 0) return false;
s = s.trim();
int state = 0;
boolean hasNum = false;
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(c>='0' && c<='9'){//digit
hasNum = true;
if(state<=2) state=2;
else state = (state<=5)? 5:7;
}
else if(s.charAt(i) == '+' || s.charAt(i)=='-'){
if(state == 0 || state == 3) state++;
else return false;
}
else if(s.charAt(i) == '.'){
if(state<=2) state = 6;
else return false;
}
else if(s.charAt(i) == 'e'){
if(state == 2 || (hasNum && state == 6) | state ==7)
state = 3;
else return false;
}
else return false;
}
return (state == 2 || state ==5 || (hasNum && state ==6) || state == 7);
}
}