问题描述:
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.
解题思路:
我觉得这里最需要搞清楚的是什么是有效的数字。而问题描述在这一方面描述的并不完全,就变成测试OJ了。
这里学习了yangf0722的DFA方法。
DFA方法的相关链接:DFA算法的简单说明与案例实现
DFA即有穷状态自动机:Deterministic Finite Automaton
在不同状态间转换跳转。这道题就很合适。
其中对于各个状态:
0:空,即输入
1 : 只包含正负号
2: 整数(包括正负)
3:以e结尾的字符串
4: e后跟正负号的字符串
5: exp表达式,即e后跟一个有效数字(整数)
6: ‘.’是最后一个出现的字符
7: 纯小数
状态转换如下图所示:
这个解法也十分简单明了https://www.cnblogs.com/zsychanpin/p/7094158.html
代码:
class Solution { public: bool isNumber(string s) { int state = 0, flag = 0; //flag to judge the special case while(s[0] == ' ') s.erase(0, 1); while(s[s.size()-1] == ' ') s.erase(s.size() - 1, 1); for(int i = 0; i < s.size(); i++){ if(s[i] - '0' > -1 && s[i] - '0' < 10){ flag = 1; if(state <= 2) state = 2; else state = state <= 5 ? 5 : 7; }else if(s[i] == '+' || s[i] == '-'){ if(state == 3 || state == 0) state++; else return false; }else if(s[i] == '.'){ if(state <= 2) state = 6; else return false; }else if(s[i] == 'e'){ if(flag&&(state==2 || state==6 || state==7)) state=3; else return false; }else return false; } return state == 2 || state == 5 || (state == 6 && flag) || state == 7; } };