题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示数值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。
解题思路
通过排除法来遍历整个字符串,不符合条件就返回False
。条件有:
e
,E
和.
均只能出现一次;+
和-
要么出现在字符串首,要么出现在e
或E
之后一位;e
或E
之后不能出现.
;e
或E
不能出现在末尾;- 不能出现非法字符。
代码
Python(2.7.3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if len(s) == 0:
return False
if s[0] == '+' or s[0] == '-':
s = s[1:]
num_exp, num_dot = 0, 0 # 分别记录'e''E'和'.'出现的次数
for idx, i in enumerate(s):
if i == 'e' or i == 'E':
if num_exp == 0:
num_exp = 1
elif num_exp == 1:
return False
if idx == len(s) - 1:
# 'e''E'出现在末尾
return False
elif i == '+' or i == '-':
if s[idx - 1] != 'e' and s[idx - 1] != 'E':
# 符号前面一个必须为'e''E'
return False
elif i == '.':
if num_dot == 0:
num_dot = 1
elif num_dot == 1:
return False
if num_exp == 1:
# '.'出现在'e''E'之后
return False
elif i not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
# 非法字符
return False
return True运行时间:23ms
占用内存:5752k
参考
https://www.nowcoder.com/questionTerminal/6f8c901d091949a5837e24bb82a731f2?toCommentId=2439883