萌新刷题(十一)有效数字

时间:2022-05-07
本文章向大家介绍萌新刷题(十一)有效数字,主要内容包括题目 给定一个字符串,验证其是否为数字。 样例、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

题目 给定一个字符串,验证其是否为数字。 样例

"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true

思路

看起来很简单,仔细一分析妈的好难。

在网上学习一些大神的思路,使用DFA来解题。

DFA是什么

DFA全称为:Deterministic Finite Automaton,即确定有穷自动机。其特征为:有一个有限状态集合和一些从一个状态通向另一个状态的边,每条边上标记有一个符号,其中一个状态是初态,某些状态是终态。但不同于不确定的有限自动机,DFA中不会有从同一状态出发的两条边标志有相同的符号。

代码

class Solution(object):
  def isNumber(self, s):
      """
      :type s: str
      :rtype: bool
      """
      #define a DFA
      state = [{}, 
              {'blank': 1, 'sign': 2, 'digit':3, '.':4}, 
              {'digit':3, '.':4},
              {'digit':3, '.':5, 'e':6, 'blank':9},
              {'digit':5},
              {'digit':5, 'e':6, 'blank':9},
              {'sign':7, 'digit':8},
              {'digit':8},
              {'digit':8, 'blank':9},
              {'blank':9}]
      currentState = 1
      for c in s:
          if c >= '0' and c <= '9':
              c = 'digit'
          if c == ' ':
              c = 'blank'
          if c in ['+', '-']:
              c = 'sign'
          if c not in state[currentState].keys():         
              return False
          currentState = state[currentState][c]      
          if currentState not in [3,5,8,9]:  
              return False
      return True

再看看更简单的

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """

        try:
            float(s)
        except ValueError:
            return False

        return True
class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        try:
            float(s)
            return True
        except:   
            return False

Python的float函数可以将一个数值或者字符转换成浮点型数值。

Python的浮点数就是数学中的小数,类似C语言中的double。

最后再知乎上发现有大佬已经写过了,倒刷LeetCode——Valid Number

人生苦短。。。Python大法好啊