leetcode 65: Valid Number
2015-08-03 13:08
363 查看
Use the FSM method:
There are 6 different types of input: space, sign, digit, dot, expo, invalid.
And the states are 1 sign, 2 digit, 3 dot, 4 digit+space, 5 digit+dot (dot+digit, digit+dot+digit), 6 digit+expo, 7 digit+expo+digit, 8 digit+expo+sign.
Only states 2, 4, 5, 7 are valid states to be finished.
class Solution {
public:
bool isNumber(string s) {
enum input
{
space,
sign,
digit,
dot,
expo,
invalid
};
int table[9][6]=
{
0,1,2,3,-1,-1,
-1,-1,2,3,-1,-1,
4,-1,2,5,6,-1,
-1,-1,5,-1,-1,-1,
4,-1,-1,-1,-1,-1,
4,-1,5,-1,6,-1,
-1,8,7,-1,-1,-1,
4,-1,7,-1,-1,-1,
-1,-1,7,-1,-1,-1,
};
int i=0,state=0;
while(i!=s.size())
{
input in=invalid;
if(s[i]==' ')
in=space;
else if(s[i]=='+'||s[i]=='-')
in=sign;
else if(s[i]>='0'&&s[i]<='9')
in=digit;
else if(s[i]=='.')
in=dot;
else if(s[i]=='e')
in=expo;
state=table[state][in];
if(state==-1)
return false;
i++;
}
return state==2||state==4||state==5||state==7;
}
};
There are 6 different types of input: space, sign, digit, dot, expo, invalid.
And the states are 1 sign, 2 digit, 3 dot, 4 digit+space, 5 digit+dot (dot+digit, digit+dot+digit), 6 digit+expo, 7 digit+expo+digit, 8 digit+expo+sign.
Only states 2, 4, 5, 7 are valid states to be finished.
class Solution {
public:
bool isNumber(string s) {
enum input
{
space,
sign,
digit,
dot,
expo,
invalid
};
int table[9][6]=
{
0,1,2,3,-1,-1,
-1,-1,2,3,-1,-1,
4,-1,2,5,6,-1,
-1,-1,5,-1,-1,-1,
4,-1,-1,-1,-1,-1,
4,-1,5,-1,6,-1,
-1,8,7,-1,-1,-1,
4,-1,7,-1,-1,-1,
-1,-1,7,-1,-1,-1,
};
int i=0,state=0;
while(i!=s.size())
{
input in=invalid;
if(s[i]==' ')
in=space;
else if(s[i]=='+'||s[i]=='-')
in=sign;
else if(s[i]>='0'&&s[i]<='9')
in=digit;
else if(s[i]=='.')
in=dot;
else if(s[i]=='e')
in=expo;
state=table[state][in];
if(state==-1)
return false;
i++;
}
return state==2||state==4||state==5||state==7;
}
};
相关文章推荐
- 一个广为人知但鲜有人用的技巧:对象池
- 心情随笔(三):注入新的血液
- Apache Commons 工具包
- vector 用法详解
- 快速幂&&快速乘法
- C# MVC3获取渲染后视图的HTML
- gem install 时报错,no such file to load -- zlib
- JAVA开发_File
- hdu5328(不用dp)
- 每天一个小程序——选择排序时的一个小问题!
- time isn't coming
- hdoj 1969 Pie
- 为什么你宁愿每周工作90小时,也不做任何改变?
- 创业型公司如何找有相同价值观的人(转)
- 如何建立压力计算模型
- 2^k进制数问题(动态规划+高精度/C++)
- HDU 2094 产生冠军 (STL:set用法)
- UVA10916取对的简单应用
- Bash里面如何返回绝对路径
- 知识管理资源