看着非常简单,leetcode上面通过率极低...
可以用正则表达式,不过面试肯定不是让你写个就ok了。。
所以我们自己来构造DFA吧。。。
写个表TAT
在各种数据的调试下,更改状态才过了(详情见照片上的修改
enum Op{ Operator, //0 Digit, // 1 E, // 2 Dot, //3 Space,// 4 Invalid }; int table[][5] = { {1,2,-1,8,-1}, {-1,2,-1,8,-1}, {-1,2,4,3,-1}, {-1,7,4,-1,-1}, {5,6,-1,-1,-1}, {-1,6,-1,-1,-1}, {-1,6,-1,-1,-1}, {-1,7,4,-1,-1}, {-1,9,-1,-1,-1}, {-1,9,4,-1,-1} }; class Solution { public: bool trim(string& s) { int start = 0; int end = s.size() - 1; while(start <= end && s[start] == ' ') start++; while(end >= 0 && s[end] == ' ') end--; if(end >= start) s = s.substr(start , end - start + 1); else return false; return true; } Op getOp(char ch) { if(ch == '+' || ch == '-') return Operator; if(ch >= '0' && ch <= '9') return Digit; if(ch == 'e') return E; if(ch == '.') return Dot; if(ch == ' ') return Space; return Invalid; } bool isNumber(const char *s) { string str = s; if(!trim(str)) return false; int pos = 0; int size = str.size(); int state = 0; while(pos < size) { char ch = str[pos]; Op x = getOp(ch); if(x == Invalid) return false; state = table[state][(int)x]; if(state == -1) return false; pos++; } return state == 2 || state == 6 || state == 7 || state == 3 || state == 9; } };