LeetCode65 Valid Number
2015-08-16 19:29
381 查看
question
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.
thinking
通信软件课上学了FSM,看到这题的时候眼前一亮,但苦于不会敲C,幸好从/article/8001175.html和https://github.com/fuwutu/LeetCode/blob/master/Valid%20Number.cpp上看到了相关解法。下图给出了部分状态转移例子(图太丑TNT)。在交题的时候发现代码是有一点点bug的,导致测试案例有的没过,这是修改之后的版本(非原创)
bool isNumber(char* s) { enum InputType { INVALID, // 0 SPACE, // 1 SIGN, // 2 DIGIT, // 3 DOT, // 4 EXPONENT, // 5 NUM_INPUTS // 6 }inputType; inputType= INVALID; int transitionTable[][NUM_INPUTS] = { -1, 0, 3, 1, 2, -1, // next states for state 0 -1, 8, -1, 1, 4, 5, // next states for state 1 -1, -1, -1, 4, -1, -1, // next states for state 2 -1, -1, -1, 1, 2, -1, // next states for state 3 -1, 8, -1, 4, -1, 5, // next states for state 4 -1, -1, 6, 7, -1, -1, // next states for state 5 -1, -1, -1, 7, -1, -1, // next states for state 6 -1, 8, -1, 7, -1, -1, // next states for state 7 -1, 8, -1, -1, -1, -1, // next states for state 8 }; int state = 0; while (*s != '\0') { if (isspace(*s)) inputType = SPACE; else if (*s == '+' || *s == '-') inputType = SIGN; else if (isdigit(*s)) inputType = DIGIT; else if (*s == '.') inputType = DOT; else if (*s == 'e' || *s == 'E') inputType = EXPONENT; else inputType=INVALID; //修改 state = transitionTable[state][inputType]; if (state == -1) return false; else ++s; } return state == 1 || state == 4 || state == 7 || state == 8; }
小结:enum的用法,transition[ ][NUM_INPUTS]数组的定义,以及最终状态的判断。
此思路值得借鉴。
try: float(s.strip()) return True except: return False
相关文章推荐
- 使用WindowManager添加您自己的自定义视图
- poj 3356
- HDU 5183 Negative and Positive (NP)(哈希 hash)——BestCoder Round #32
- unity3d PlayerPrefs
- dijstra(迪杰斯特拉)算法的简单实现
- 不能打开参数文件initORCL.ora解决办法
- 【POJ2151】【Check the difficulty of problems】
- 阿里云RDS(云数据库)之产品简介
- Neighbor House
- Xcode快捷键大全
- web.xml 中 classpath 写法说明
- 【IOS开发笔记03-视图相关】简单计算器的实现
- (4)java方法区
- HDOJ 4857 逃生 (逆向拓扑排序)
- 万能的知乎(下):当“水化”危机不可避免,拯救知乎的一千种可能
- Python生成验证码
- CentOS单独编译安装PHP gd库扩展
- foreach遍历----for(object o: list)
- I Hate It
- java正则表达式