LeetCode解题心得——表示数值的字符串(python)

题目

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"都表示数值,但"12e”、“1a3.14”、“1.2.3”、“±5”、"-1E-16"及"12e+5.4"都不是。

思路

确定有限自动机
LeetCode解题心得——表示数值的字符串(python)_第1张图片

class Solution:
    def isNumber(self, s: str) -> bool:
        table = [[2,1,-1,0,3,-1],
                 [-1,1,6,9,4,-1],
                 [-1,1,-1,-1,10,-1],
                 [-1,5,-1,-1,-1,-1],
                 [-1,5,6,9,-1,-1],
                 [-1,5,6,9,-1,-1],
                 [8,7,-1,-1,-1,-1],
                 [-1,7,-1,9,-1,-1],
                 [-1,7,-1,-1,-1,-1],
                 [-1,-1,-1,9,-1,-1],
                 [-1,5,-1,-1,-1,-1]]
        mapp = {
            'sign':0,
            'digit':1,
            'e':2,
            'blank':3,
            '.':4,
            'other':5
        }
        def get_map(element):
            if element in ['-','+']: return 'sign'
            if element.isdigit(): return 'digit'
            if element in ['e','E']: return 'e'
            if element == ' ': return 'blank'
            if element == '.': return '.'
            else: return 'other'
        
        state = 0
        for i in s:
            state = table[state][mapp[get_map(i)]]
            if state == -1: return False
        return state in [1,5,7,4,9]

你可能感兴趣的:(LeetCode)