博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Valid Number
阅读量:4557 次
发布时间:2019-06-08

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

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.

Solution: This finite-state machine solution. Learn from fuwutu & snakeDling.

1 class Solution { 2 public: 3     bool isNumber(const char *s) { 4         enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT}; 5         int transitionTable[][6] =  6         { /* 0   1   2   3   4   5  */ 7              0,  1,  2,  3,  4,  0, // 0: INVALID 8              0,  1,  2,  3,  4,  0, // 1: SPACE 9              0,  0,  0,  3,  4,  0, // 2: SIGN10              0,  6,  0,  3,  7,  5, // 3: DIGIT11              0,  0,  0,  7,  0,  0, // 4: DOT12              0,  0,  2,  8,  0,  0, // 5: EXPONENT13              0,  6,  0,  0,  0,  0, // 6: END WITH SPACE14              0,  6,  0,  7,  0,  5, // 7: DOT AND DIGIT15              0,  6,  0,  8,  0,  0, // 8: END WITH SPACE OR DIGIT16         };17         18         InputType last = INVALID;19         while (*s != '\0')20         {21             InputType state = INVALID;22             if (*s == ' ')23                 state = SPACE;24             else if (isdigit(*s))25                 state = DIGIT;26             else if (*s == '+' || *s == '-')27                 state = SIGN;28             else if (*s == 'e')29                 state = EXPONENT;30             else if (*s == '.')31                 state = DOT;32             last = (InputType) transitionTable[last][state];33             if (last == INVALID) return false;34             s++;35         }36         bool validFinal[] = {
0, 0, 0, 1, 0, 0, 1, 1, 1};37 return validFinal[last];38 }39 };

 

转载于:https://www.cnblogs.com/zhengjiankang/p/3679641.html

你可能感兴趣的文章
MySQL无法存储Emoji表情问题
查看>>
HDFS集中式的缓存管理原理与代码剖析
查看>>
POJ1019 Number Sequence
查看>>
第十七章-异步IO
查看>>
Linux就该这么学
查看>>
out传值
查看>>
CentOS6.8【环境配置篇】
查看>>
线程同步的方式
查看>>
Mongodb 安装
查看>>
WPF窗口贴边隐藏(类似QQ)
查看>>
VS2008无法切换到视图设计器
查看>>
爱情故事:追忆似水流年 回味永恒的爱恋
查看>>
android mvn android:deploy签名问题
查看>>
transient
查看>>
[HDU 4348]To the moon
查看>>
初识【Windows API】--文本去重
查看>>
[转]IOS多线程
查看>>
详解spl_autoload_register() 与 __autoload
查看>>
Axure RP Extension for Chrome安装
查看>>
day_10
查看>>