牛客-剑指offer系列题解:表示数值的字符串

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
2、数据结构:
数组

3、题解:
牛客-剑指offer系列题解:表示数值的字符串_第1张图片
牛客-剑指offer系列题解:表示数值的字符串_第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

你可能感兴趣的:(牛客-剑指offer系列题解)