LeetCode 65 ValidNumer(Python详解及实现)
来源:互联网 发布:java带毫秒 编辑:程序博客网 时间:2024/05/16 08:48
【题目】
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 problemstatement to be ambiguous. You should gather all requirements up front beforeimplementing one.
输入一个字符串,判断这个字符串表示的是不是一个有效的数字。比如:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
【思路】
这个题目难点在于考虑要全面,空格在字符串两端不影响;在字符串中间出现为false;正负号在第一个出现的数字前出现为True;正负号在E或e之后出现且后面有数字的为true;E或e出现在数字中间,两边均为数字才合理。
【Python实现】
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
begin, last = 0, len(s) - 1
while begin <= last and s[begin] == ' ':#若起始为空格,下移一位判断
begin += 1
while begin <= last and s[last] == ' ':#若末尾为空格,上移一位判断
last -= 1
'''if begin < last and (s[begin] == '+' or s[begin] == '-'):#如果当前位为正号或符号,下移一位检测下一位是否为数字
begin += 1'''
num, dot, exp = False, False, False#数字,点,exp标志位
start = begin#记录下最开始不是空格的位置
while begin <= last:
if s[begin] >= '0' and s[begin] <= '9':#检测当前位是否为数字
num = True
elif s[begin] == '.' :
#if begin != last:
#return False
if dot or exp:
print(1)
return False
dot = True
elif s[begin] == 'e' or s[begin] == 'E':
if exp or not num:
print(2)
return False
exp,num = True,False
elif s[begin] == '+' or s[begin] == '-':
if begin != start and s[begin- 1] != 'e':
#首个是符号,或者当前字符为符号时候若前一个字符不是e,直接返回
return False
else:
print(4)
return False
begin += 1
print(5)
return num
if __name__ == '__main__':
S= Solution()
s= ' -54.53061'
S.isNumber(s)
- LeetCode 65 ValidNumer(Python详解及实现)
- LeetCode 75 SortColor(Python详解及实现)
- LeetCode 77 Combinations (Python详解及实现)
- LeetCode 78 Subsets (Python详解及实现)
- LeetCode 90 SubsetsII (Python详解及实现)
- LeetCode 55 Jump Game(Python 实现及详解)
- LeetCode 56 Merge Intervals(Python实现及详解)
- LeetCode 60 Permutation Sequence (Python实现及详解)
- LeetCode 61. Rotate List(Python详解及实现)
- LeetCode 66 Plus One (Python详解及实现)
- LeetCode 68 Text Justification(Python详解及实现)
- LeetCode 70 Climbing Stairs(Python详解及实现)
- LeetCode 71 Simplify Path(Python详解及实现)
- LeetCode 72 Edit Distance(Python详解及实现)
- LeetCode 73 Set Matrix Zeroes(Python详解及实现)
- LeetCode 76 Minimum Window Substring(Python详解及实现)
- LeetCode 79 Word Search (Python详解及实现)
- LeetCode 84 Largest Rectangle in Histogram (Python详解及实现)
- Java中OutOfMemoryError(内存溢出)的三种情况及解决办法
- Flume 以twitter为source,kafka为channel,hdfs为sink,再用spark streaming 读kafka topic
- 51nod 1277 字符串中的最大值【KMP算法】【next树】
- 发现MSDN文档错误
- 在ruby中&到底是什么呢?
- LeetCode 65 ValidNumer(Python详解及实现)
- word break/pattern/ladder
- struts2框架学习笔记01
- LeetCode
- 深度学习中30个关于数据的问题
- 【Java】封装httpClient
- 构造HTTP请求Header实现"伪造来源IP"
- Java 异常处理
- python中scipycluster库简介