博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
有限状态机框架php,Leetcode 65 Valid Number DFA有限状态机
阅读量:7025 次
发布时间:2019-06-28

本文共 1288 字,大约阅读时间需要 4 分钟。

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⑴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]={

{⑴, 0, 1, 2, ⑴, 3},

{⑴, ⑴, ⑴, 2, ⑴, 3},

{⑴, ⑴, ⑴, ⑴, ⑴, 4},

{⑴, 5, ⑴, 4, 6, 3},

{⑴, 5, ⑴, ⑴, 6, 4},

{⑴, 5, ⑴, ⑴, ⑴, ⑴},

{⑴, ⑴, 7, ⑴, ⑴, 8},

{⑴, ⑴, ⑴, ⑴, ⑴, 8},

{⑴, 5, ⑴, ⑴, ⑴, 8}

};

int now=0;

for(int i=0;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 ;

}

};

转载地址:http://vksxl.baihongyu.com/

你可能感兴趣的文章
shell 基础
查看>>
阿里云镜像服务:基于Tag的Docker自动构建
查看>>
map的排序总结
查看>>
ExtJs之Ext.core.DomQuery
查看>>
使用chain方式,在第二action中获取第一个action中actionMessage
查看>>
CentOS安装及配置DNS服务器
查看>>
淘宝Diamond架构分析
查看>>
IE8 jquery ajax获取静态资源报错TypeError 拒绝访问
查看>>
创建完美SDK的10个技巧
查看>>
5、spss做加权最小二乘回归及岭回归
查看>>
Map 按key和value 排序
查看>>
每周一道数据结构(一)图
查看>>
Android 5.x特性概览四
查看>>
归并排序MergeSort
查看>>
十五天精通WCF——第二天 告别烦恼的config配置
查看>>
CYQ.Data 轻量数据访问层(四) 构造数据单元列
查看>>
精美UI界面欣赏[12]
查看>>
UIButton的两种block传值方式
查看>>
深蓝词库转换1.5发布
查看>>
ORA-01033: ORACLE initialization or shutdown in progress
查看>>