LeetCode Valid Number
2016-01-22 19:47
218 查看
LeetCode解题之Valid Number
原题
判断一个字符串是否是数值类型的。这里的数值类型除了一般要考虑的小数、正负数外还要考虑科学计数法e,如” -3.2e-23 “是数值类型的。注意点:
小数点前和后没有数字都是合法的
科学计数法后面也可以是负数
例子:
输入: s = ” -3.2e-23 “
输出: True
解题思路
比较恶心的一道题,没有明确给出定义,给了一些例子,需要自己不断去尝试。首先要把前后的空字符给去掉。然后依次考虑符号、数字、小数点、数字,如果有这些中连续的几个,表示目前是一个普通的数值。继续判断”e”(注意大小写都可以),接着判断符号、数字,如果e后面没有数字,那么这是一个不正常的科学类数值。最后根据三种情况来综合判断,要满足目标是一个数值类型,那么首先要保证e前面的数是正常的,如果有e的话,要保证它后面的数也是正常的,最后要保证整个字符串都已经遍历玩了,如果没有说明中间出现了一些异常的字符或者末尾多了一些多余的字符。AC源码
[code]class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ s = s.strip() length = len(s) index = 0 # Deal with symbol if index < length and (s[index] == '+' or s[index] == '-'): index += 1 is_normal = False is_exp = True # Deal with digits in the front while index < length and s[index].isdigit(): is_normal = True index += 1 # Deal with dot ant digits behind it if index < length and s[index] == '.': index += 1 while index < length and s[index].isdigit(): is_normal = True index += 1 # Deal with 'e' and number behind it if is_normal and index < length and (s[index] == 'e' or s[index] == 'E'): index += 1 is_exp = False if index < length and (s[index] == '+' or s[index] == '-'): index += 1 while index < length and s[index].isdigit(): index += 1 is_exp = True # Return true only deal with all the characters and the part in front of and behind 'e' are all ok return is_normal and is_exp and index == length if __name__ == "__main__": assert Solution().isNumber("3.e-23") == True assert Solution().isNumber(".2e81") == True assert Solution().isNumber("2e10") == True assert Solution().isNumber(" 0.1") == True assert Solution().isNumber("1 b") == False assert Solution().isNumber("3-2") == False assert Solution().isNumber("abc") == False
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- LeetCode: Unique Binary Search Trees [095]
- 往github上传demo
- CKEditor使用总结(持续更新)
- 煲耳机,看到一篇文章分享下
- 《剑指offer》 学习笔记(一)
- [C++] 多态性与虚函数
- jQuery选择器下
- 编码和加密算法的使用(MD5、Base64、DES、RSA)
- s7-1200学习琐记(3)
- 0122有关List、Set、Map的练习
- 博客园知识库-好文章
- eclipse的优势对比vi、npp等代码编辑软件
- C语言小结
- Android利用AccessibilityService实现自动装总结(二)
- golang为LigerUI编写简易版本web服务器
- 阿里云服务器Linux环境下安装MySQL5.7.10
- apache httpd基础
- Linux平台上最常用的翻译工具—StarDict(星际译王)。
- 忘记XP密码的解决方案
- JavaSE-模板方法设计模式