文章目录
剑指 Offer 20. 表示数值的字符串
打补丁打到绝望
def isNumber(self, s: str) -> bool:
m = [str(i) for i in range(10)]
m += ['+', '-', 'e', 'E', '.']
res = s.strip()
for cha in res:
if cha not in m: return False
for cha in res:
if cha == '.' or cha == 'e' or cha == 'E': return self.isEeDot(cha, res)
return self.isInt(s)
def isInt(self, ss):
try: int(ss)
except: return False
else: return True
def isEeDot(self, cha, res):
if len(res) == 0 or len(res) == 1: return False
if cha in res:
li = res.split(cha)
else: return True
if len(li) != 2: return False # 保证只有一个e/E/.
if li[0] == '' and cha == 'e': return False
elif li[0] == '' and cha == 'E': return False
if cha == 'e' or cha == 'E':
if self.isInt(li[-1]) and self.isInt(li[0]): return True
else: return False
if not self.isInt(li[-1]): return False # e/E后值必须是整数
elif cha == '.':
if ' ' in li[-1] or ' ' in li[0]: return False
if 'e' in li[-1]: return self.isEeDot('e', li[-1])
elif 'E' in li[-1]: return self.isEeDot('E', li[-1])
elif '-' in li[-1] or '+' in li[-1]: return False
else: return self.isInt(li[-1]) or self.isInt("".join(li[0]))
下面是大佬的代码和思路:
大佬,代码:
class Solution:
def isNumber(self, s: str) -> bool:
states = [
{ ' ': 0, 's': 1, 'd': 2, '.': 4 }, # 0. start with 'blank'
{ 'd': 2, '.': 4 } , # 1. 'sign' before 'e'
{ 'd': 2, '.': 3, 'e': 5, ' ': 8 }, # 2. 'digit' before 'dot'
{ 'd': 3, 'e': 5, ' ': 8 }, # 3. 'digit' after 'dot'
{ 'd': 3 }, # 4. 'digit' after 'dot' (‘blank’ before 'dot')
{ 's': 6, 'd': 7 }, # 5. 'e'
{ 'd': 7 }, # 6. 'sign' after 'e'
{ 'd': 7, ' ': 8 }, # 7. 'digit' after 'e'
{ ' ': 8 } # 8. end with 'blank'
]
p = 0 # start with state 0
for c in s:
if '0' <= c <= '9': t = 'd' # digit
elif c in "+-": t = 's' # sign
elif c in "eE": t = 'e' # e or E
elif c in ". ": t = c # dot, blank
else: t = '?' # unknown
if t not in states[p]: return False
p = states[p][t]
return p in (2, 3, 7, 8)
这道题回头再翻回来看吧。
剑指 Offer 67. 把字符串转换成整数
我写的垃圾代码,写不动了也。
def strToInt(self, str: str) -> int:
comp = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
comp.extend(['-', '+'])
cur = 0
res = []
symbol = 0
while cur < len(str):
while str[cur] == ' ': cur += 1
if str[cur] not in comp: return 0
if str[cur] == '+' or str[cur] == '-': symbol += 1
if symbol > 1: return 0
res.append(str[cur])
cur += 1
return int("".join(res))
大佬代码:
class Solution:
def strToInt(self, str: str) -> int:
str = str.strip() # 删除首尾空格
if not str: return 0 # 字符串为空则直接返回
res, i, sign = 0, 1, 1
int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
if str[0] == '-': sign = -1 # 保存负号
elif str[0] != '+': i = 0 # 若无符号位,则需从 i = 0 开始数字拼接
for c in str[i:]:
if not '0' <= c <= '9' : break # 遇到非数字的字符则跳出
if res > bndry or res == bndry and c > '7': return int_max if sign == 1 else int_min # 数字越界处理
res = 10 * res + ord(c) - ord('0') # 数字拼接
return sign * res
明天起来我再自己写一遍。