记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
2、数据结构:
数组
# -*- coding:utf-8 -*-
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
if not s: return False
transTable = [
[1, 2, 7, -1, -1, 0],
[-1, 2, 7, -1, -1, -1],
[-1, 2, 3, 4, -1, 9],
[-1, 3, -1, 4, -1, 9],
[6, 5, -1, -1, -1, -1],
[-1, 5, -1, -1, -1, 9],
[-1, 5, -1, -1, -1, -1],
[-1, 8, -1, -1, -1, -1],
[-1, 8, -1, 4, -1, 9],
[-1, -1, -1, -1, -1, 9]
]
cols = {
"sign": 0,
"number": 1,
".": 2,
"exp": 3,
"other": 4,
"blank": 5
}
def get_col(c):
if c.isdigit():
return 'number'
elif c in {'+', '-'}:
return 'sign'
elif c == '.':
return '.'
elif c in {'E', 'e'}:
return 'exp'
elif c == ' ':
return 'blank'
else:
return 'other'
legal_state = {2, 3, 5, 8, 9}
state = 0
for c in s:
state = transTable[state][cols[get_col(c)]]
if state == -1: return False
return True if state in legal_state else False