Leetcode 65 Valid Number DFA有限状态机
来源:互联网 发布:上知教育幼小衔接好吗 编辑:程序博客网 时间:2024/05/21 18:36
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.
判断数字的合法性
刚开始是把它作为一道细节较多的模拟题做的,通过后去discuss看了一下,果然有优美的解答!
用有限状态机DFA解决,将每一位看成一种状态转移条件,每次读取的一位,就根据转移矩阵进行状态转移,若转移到不合法的状态则返回false。
思路简单优美,不用考虑多余的细节问题,刷了这么多leetcode,这题真的眼前一亮!
具体的状态说明可以看这篇博客
class Solution {public: bool isNumber(string s) { int mp[9][6]={ {-1, 0, 1, 2, -1, 3}, {-1, -1, -1, 2, -1, 3}, {-1, -1, -1, -1, -1, 4}, {-1, 5, -1, 4, 6, 3}, {-1, 5, -1, -1, 6, 4}, {-1, 5, -1, -1, -1, -1}, {-1, -1, 7, -1, -1, 8}, {-1, -1, -1, -1, -1, 8}, {-1, 5, -1, -1, -1, 8} }; int now=0; for(int i=0;i<s.size();i++) { switch(s[i]) { case '-': now=mp[now][2];break; case '+': now=mp[now][2];break; case ' ': now=mp[now][1];break; case '.': now=mp[now][3];break; case 'e': now=mp[now][4];break; case 'E': now=mp[now][4];break; default: { if(s[i]>='0' && s[i]<='9') now=mp[now][5]; else now=mp[now][0]; } } if(now==-1) return false; } return now==3 || now==4 || now==5 || now==8 ; }};
1 0
- Leetcode 65 Valid Number DFA有限状态机
- LeetCode-Valid Number - 有限状态机
- LeetCode-Valid Number - 有限状态机
- [LeetCode] Valid Number 有限状态机解法
- [LeetCode] Valid Number 使用有限状态机
- LeetCode-Valid Number - 有限状态机 & 正则表达式
- 65 - Valid Number(DFA-Deterministic Finite Automaton)
- Valid Number - 有限状态机
- Valid Number-有限状态机/正则表达式
- leetcode ||65、 Valid Number
- LeetCode #65 Valid Number
- leetcode 65: Valid Number
- Leetcode#65||Valid Number
- leetcode|Valid Number(65)
- leetcode-65-Valid Number
- LeetCode 65 - Valid Number
- LeetCode 65 Valid Number
- Leetcode 65 Valid Number
- [ LeetCode ] - 136. Single Number 解答
- Unity手势插件FingerGestures使用遇到的问题
- 方便的读取配置项类
- jQuery 语法
- cookie,localStorage和sessionStorage三兄弟
- Leetcode 65 Valid Number DFA有限状态机
- 语音信号处理之(一)动态时间规整(DTW)
- opencv3编程入门学习笔记-----图像的载入、显示和输出到文件
- Objective-UIImageView的创建和使用(带动画效果)
- 听说你在做斗鱼APP?
- Android 开发中调用google语音接口
- Spring+Mybatis透明实现读写分离
- Android Handler解析
- php中事务简单实例