加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Leetcode 65 Valid Number DFA有限状态机

发布时间:2020-12-13 21:14:03 所属栏目:PHP教程 来源:网络整理
导读:Validate if a given string is numeric. Some examples: 0 = true 0.1 = abc = false 1 a = 2e10 = true Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. Update

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => "abc" => false
"1 a" => "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⑴0):

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.

判断数字的合法性

刚开始是把它作为1道细节较多的摹拟题做的,通过后去discuss看了1下,果然有优美的解答!

用有限状态机DFA解决,将每位看成1种状态转移条件,每次读取的1位,就根据转移矩阵进行状态转移,若转移到不合法的状态则返回false。

思路简单优美,不用斟酌过剩的细节问题,刷了这么多leetcode,这题真的眼前1亮!

具体的状态说明可以看这篇博客

class Solution { public: bool isNumber(string s) { int mp[9][6]={ {⑴,1,2,⑴,3},{⑴,4},5,4,6,⑴},7,8},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==⑴) return false; } return now==3 || now==4 || now==5 || now==8 ; } };


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读