讨论/技术交流/刷leetcode真是磨炼心智/
刷leetcode真是磨炼心智

今天碰到一道题:
https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
image.png
第一次写状态机,密密麻麻纸上画了一大面

class Solution:
    def isNumber(self, s: str) -> bool:
        states = [
            { ' ': 0, 's': 1,'d': 2,'.':4},         #0
            { 'd': 2, '.': 4 },                #1
            { 'd': 2, '.': 3, ' ': 9,'e':6 },        #2
            { 'd': 5, 'e':6, ' ': 9 },                #3
            { 'd': 5 },                        #4                  
            { 'd': 5,'e': 6, ' ': 9 },                #5
            { 's': 10,'d': 7 },                        #6
            { 'd': 7, '.':8,' ': 9 },          #7
            { 'd': 8} ,                        #8
            { ' ': 9} ,                         #9
            { 'd': 7}
        ]
        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, 5, 7, 9)

完成是面向错误编程。。。。最后绿的那刻,终于解脱了
image.png

5
共 2 个回复

这道题确实很难的

在下佩服😎😎😎

1