请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、“±5”、"-1E-16"及"12e+5.4"都不是。
注意:本题与主站 65 题相同:https://leetcode-cn.com/problems/valid-number/
通过次数12,478提交次数60,696
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
有限自动状态机,关键在于画出状态转换图,然后根据状态图选择合适的数据结构,一般是map,构建状态转换的表,之后不断进行状态转换,最后根据最后的状态来确定是否满足要求。
画状态转换图的方法,1.先列出所有的合法的引起状态转换的输入;2.从零开始对每个位置向后进行状态转换,直到不能转换位置;3.合并状态转换图,将拥有一样的向下转换的节点进行合并,即可获得最后的状态转换图。
u1s1这图可太难画了,ps,本题中.32也属于合法的输入
图片来源于题解区,https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/solution/mian-shi-ti-20-biao-shi-shu-zhi-de-zi-fu-chuan-y-2/
这个大佬巨牛逼
class Solution {
public:
bool isNumber(string s) {
//有限自动状态转换机
vector<unordered_map<char,int>> states;
unordered_map<char,int> temp;
//0.状态
temp[' '] = 0;
temp['s'] = 1;
temp['.'] = 4;
temp['d'] = 2;
states.push_back(temp);
temp.clear();
//1.状态
temp['d'] = 2;
temp['.'] = 4;
states.push_back(temp);
temp.clear();
//2.状态
temp['e'] = 5;
temp['d'] = 2;
temp['.'] = 3;
temp[' '] = 8;
states.push_back(temp);
temp.clear();
//3.状态
temp['d'] = 3;
temp['e'] = 5;
temp[' '] = 8;
states.push_back(temp);
temp.clear();
//4.状态
temp['d'] = 3;
states.push_back(temp);
temp.clear();
//5.状态
temp['d'] = 7;
temp['s'] = 6;
states.push_back(temp);
temp.clear();
//6.状态
temp['d'] = 7;
states.push_back(temp);
temp.clear();
//7.状态
temp['d'] = 7;
temp[' '] = 8;
states.push_back(temp);
temp.clear();
//8.状态
temp[' '] = 8;
states.push_back(temp);
temp.clear();
int state = 0;
for(auto c:s)
{
unordered_map<char,int>::iterator iter;
if(c-'0'>=0&&c-'0'<=9)c = 'd';
if(c=='+'||c=='-')c = 's';
iter = states[state].find(c);
if(iter == states[state].end())return false;
state = iter->second;
}
if(state==2||state==3||state==7||state==8)return true;
return false;
}
};