算法-leetcode-65-Valid Number

上代码:

# coding:utf-8

__author__ = "sn"

"""
Validate if a given string is numeric.

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

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

"""

"""
思路:

1.float()...

2.去空格,正则匹配
首位是否为+或-
数字
^[0-9]{1,}[\.]{0,1}[0-9]{0,}$
^\.[0-9]{1,}$
科学计数
^[0-9]{1,}[\.]{0,1}[0-9]*e[0-9]+$

3.类似正则
合法的数字表达式有以下几种:
全数字
.全数字
数字.数字
数字e[+-]数字

按.和e作分割点,分别进行判断是否合规
先将两端的空格去掉,首字符是否为+-
判断是否数字,如果不是直接返回False,
遇到'.',判断.后是否有一列数字
遇到‘e',然后判断'e'以后是否有’+‘,’-‘
判断后续的是否是数字。
使用 if else 即可
注意边界情况;

4.把方法3的过程抽象化,得到有穷状态自动机DFA
结合本题,字符串有9种状态比较合适:
0 无输入或只有空格
1 输入了数字

2 无数字,只有dot

3只输入了符号+或-
4 有数字有dot
5 e或者E输入后的状态
6 输入e之后输入sign的状态
7 输入e之后输入数字的状态
8 有效数字输入后,输入空格判断合法输入结束

状态机简图:

"""

class Solution:

  #方法3
  def isNumber(self, s):
    """
    :type s: str
    :rtype: bool
    """

    begin, last = 0, len(s)-1
    # 去首尾空格
    while begin <= last and s[begin] == " ":
      begin += 1
    while last >= begin and s[last] == " ":
      last -= 1

    # 首位是否为+或-
    if begin < last and (s[begin] == "+" or s[begin] == "-"):
      begin += 1

    num, dot, exp = False, False, False
    

    # 主体校验
    while begin <= last:
      if s[begin] >= "0" and s[begin] <= "9":
        num = True
      elif s[begin] == ".":
        if dot or exp:
          return False
        dot = True
      elif s[begin] == "e" or s[begin] == "E":
        if exp or not num:
          return False
        exp, num = True, False
      elif s[begin] == "+" or s[begin] == "-":
        if not(s[begin-1] == "e" or s[begin-1] == "E"):
          return False
      else:
        return False
      begin += 1
    return num

# 方法4-1
# 有限状态自动机
  def isNumber(self, s):
    INVALID = 0;SPACE = 1; SIGN = 2; DIGIT = 3; DOT = 4; EXPONENT = 5;

    transitionTable = [[-1, 0, 3, 1, 2, -1],
      [-1, 8, -1, 1, 4, 5],
      [-1, -1, -1, 4, -1, -1],
      [-1, -1, -1, 1, 2, -1],
      [-1, 8, -1, 4, -1, 5],
      [-1, -1, 6, 7, -1, -1],
      [-1, -1, -1, 7, -1, -1],
      [-1, 8, -1, 7, -1, -1],
      [-1, 8, -1, -1, -1, -1]]

    state = 0; i = 0
    while i < len(s):
      inputtype = INVALID
      if s[i] == ' ':
        inputtype = SPACE
      elif s[i] == '-' or s[i] == '+':
        inputtype = SIGN
      elif s[i] in '0123456789':
        inputtype = DIGIT
      elif s[i] == '.':
        inputtype = DOT
      elif s[i] == 'e' or s[i] == 'E':
        inputtype = EXPONENT

      state = transitionTable[state][inputtype]
      if state == -1:
        return False
      else:
        i += 1
    return state == 1 or state == 4 or state == 7 or state == 8

# 方法4-2
# 换一种方式实现DFA
  def isNumber(self, s):
    """
    :type s: str
    :rtype: bool
    """
    # define a DFA
    state = [
      {"space": 0, "digit": 1, "sign": 3, ".": 2},
      {"digit": 1, "space": 8, "e": 5, ".": 4},
      {"digit": 4},
      {"digit": 1, ".": 2},
      {"digit": 4, "e": 5, "space": 8},
      {"digit": 7, "sign": 6},
      {"digit": 7},
      {"digit": 7, "space": 8},
      {"space": 8}]

    currentstate = 0
    for c in s:
      if c >= "0" and c <= "9":
        c = "digit"
      elif c == " ":
        c = "space"
      elif c in ["+", "-"]:
        c = "sign"
      elif c in ["e", "E"]:
        c = "e"
      # if c == ".":
        # c ="."

      if c not in state[currentstate].keys():
        return False
      currentstate = state[currentstate][c]

    if currentstate in [1, 4, 7, 8]:
      return True
    else:
      return False

if __name__ == "__main__":
  res = Solution()
  str_num = "4.7e7"
  result = res.isNumber(str_num)
  if result:
    print("is number.")
  else:
    print("is not number.")

算法-leetcode-65-Valid Number的更多相关文章

  1. [leetcode]65. Valid Number 有效数值

    Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...

  2. leetCode 65.Valid Number (有效数字)

    Valid Number  Validate if a given string is numeric. Some examples: "0" => true " ...

  3. [LeetCode] 65. Valid Number 验证数字

    Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...

  4. LeetCode 65 Valid Number

    (在队友怂恿下写了LeetCode上的一个水题) 传送门 Validate if a given string is numeric. Some examples: "0" =&g ...

  5. Leetcode 65 Valid Number 字符串处理

    由于老是更新简单题,我已经醉了,所以今天直接上一道通过率最低的题. 题意:判断字符串是否是一个合法的数字 定义有符号的数字是(n),无符号的数字是(un),有符号的兼容无符号的 合法的数字只有下列几种 ...

  6. [LeetCode] 65. Valid Number(多个标志位)

    [思路]该题题干不是很明确,只能根据用例来理解什么样的字符串才是符合题意的,本题关键在于几个标志位的设立,将字符串分为几个部分,代码如下: class Solution { public: strin ...

  7. 【LeetCode】65. Valid Number

    Difficulty: Hard  More:[目录]LeetCode Java实现 Description Validate if a given string can be interpreted ...

  8. 【leetcode】Valid Number

    Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...

  9. 【一天一道LeetCode】#65. Valid Number

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Validat ...

  10. 65. Valid Number

    题目: Validate if a given string is numeric. Some examples:"0" => true" 0.1 " = ...

随机推荐

  1. 传奇版本中利用NPC迅速给人物加血脚本制作

    在传奇中,快速给玩家回血的脚本被广泛运用,能刺激玩家消费,怎么说呢,玩家跟人PK激情中,特别是群打,快速补血的重要性不说你也懂的. [@main]神医:“最近玛法大陆动荡不平,每天进进出出这里的伤者日 ...

  2. ILM --interface logic model

    1.描述接口逻辑的模型. 2.包括 netlist  spef sdc def 3.所有以上文件只描述和接口相关的逻辑,其他逻辑一概排除 3.用于STA/PR/DC的hierachical flow, ...

  3. Django 无法同步数据库model相应字段问题

    前言:今天也是充满bug的一天,脸上笑嘻嘻....(继续,讲文明,懂礼貌) 1,问题描述,models中的字段设置的是浮点型,但是输出的结果总是int()类型 models average_score ...

  4. SpringBoot-自动装载

    1,SpringBoot里面有内置的tomcat容器. 2,SpringBoot是基于已有的东西创建的新的东西.核心:(AutoConfiguration)自动装载,Starter,Actuator, ...

  5. 将训练好的Tensorflow模型部署到web应用中

    做一个简易web使用Flask是最好的选择,不仅上手快,使用也很便利.Django很强大也很好用,但一次就会创建一个项目的所需的文件,我觉得对于测试一个模型在web端有没有效果没必要用它. flask ...

  6. 为什么局部内部类和匿名内部类只能访问 final 的局部变量?

    首先,我们看一个局部内部类的例子: class OutClass { private int age = 12; public void outPrint(final int x) { class I ...

  7. ASP.NET Core搭建多层网站架构【11-WebApi统一处理返回值、异常】

    2020/02/01, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[11-WebApi统一处理返回值.异常] 使用I ...

  8. Vue如何用虚拟dom进行渲染view的

    前提 vue版本:v2.5.17-beta.0 触发render vue在数据更新后会自动触发view的render工作,其依赖于数据驱动:在数据驱动的工作下,每一个vue的data属性都被监听,并且 ...

  9. Java入门笔记 09-集合

    一.Collection接口方法:Collection 接口是 List.Set 和 Queue 接口的父接口,该接口里定义的方法既可用于操作 Set 集合,也可用于操作 List 和 Queue 集 ...

  10. 登录oracle ORA-12541: TNS:no listener报错

    初次安装Oracle是通过VMware在虚拟机上安装的,安装Oracle过程,解锁了两个用户,分别是Scott和HR,也设置了密码,安装完成后输入sqlplus scott/admin123(scot ...