简繁EN

LeetCodeNo. 136

[LeetCode with Python] 65. Valid Number

Contents

Problem

Problem page: https://leetcode.com/problems/valid-number/
Topics: Math, String
Difficulty: hard
Similar problems: (E) String to Integer (atoi)

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.


Analysis

A finite automaton (DFA). Come to think of it, could I solve this with an NFA? What are the limits of using an NFA?


Code

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
36
37
38
39
40
41
42
43
class Solution:
def getType(self, ch):
if ' ' == ch:
return 1
elif '+' == ch or '-' == ch:
return 2
elif ch >= '0' and ch <= '9':
return 3
elif '.' == ch:
return 4
elif 'e' == ch:
return 5
else:
return 7

def getMap(self):
map = (
(0, 0, 1, 4, 2, -1, -1, -1), # 0: ^ / space
(-1, -1, -1, 4, 2, -1, -1, -1), # 1: + / -
(-1, -1, -1, 3, -1, -1, -1, -1), # 2: .
(-1, 10, -1, 3, -1, 7, 11, -1), # 3: num
(-1, 10, -1, 4, 5, 7, 11, -1), # 4: num
(-1, 10, -1, 6, -1, 7, 11, -1), # 5: .
(-1, 10, -1, 6, -1, 7, 11, -1), # 6: num
(-1, -1, 8, 9, -1, -1, -1, -1), # 7: e
(-1, -1, -1, 9, -1, -1, -1, -1), # 8: + / 1
(-1, 10, -1, 9, -1, -1, 11, -1), # 9: num
(-1, 10, -1, -1, -1, -1, 11, -1) # 10: space
)
return map

# @param s, a string
# @return a boolean
def isNumber(self, s):
map = self.getMap()
state = map[0][0] # begin marker, fed as a type rather than a character
for ch in s:
type = self.getType(ch)
state = map[state][type]
if -1 == state:
return False
state = map[state][6] # end marker, fed as a type rather than a character
return 11 == state

Article link: https://xnerv.wang/en/leetcode-valid-number/