算法-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. Git - 05. git log & git show

    1. 概述 有了提交, 就必须有日志 日志用处很多, 这里我就不多说了 2. 项目日志 概述 查看当前分支的 提交记录 命令 普通查看 命令 > git log 显示 commit id 包括 ...

  2. Codeforces Round #604 (Div. 2)D(构造)

    构造,枚举起点,如果一个序列成立,那么将它reverse依然成立,所以两个方向(从小到大或从大到小)没有区别,选定一个方向进行探测,直到探测不到以后回头,只要所给数据能成立,那么能探测进去就能探测出来 ...

  3. app内区域截图利用html2Canvals保存到手机 截屏 (html2Canvas使用版本是:0.5.0-beta3。)

    app内区域截图利用html2Canvals保存到手机 app内有时候需要区域内的截图保存dom为图像,我们可以使用html2Canvas将dom转换成base64图像字符串,然后再利用5+api保存 ...

  4. 清除定时器 和 vue 中遇到的定时器setTimeout & setInterval问题

    2019-03更新 找到了更简单的方法,以setinterval为例,各位自行参考 mounted() { const that = this const timer = setInterval(fu ...

  5. PyCharm安装及汉化设置为中文(附汉化包)

    下载:https://www.jetbrains.com/pycharm/download/#section=windows 下载社区版免费 双击运行安装程序 Next 选择安装路径安装 创建桌面快捷 ...

  6. Integer数值小于127时使用==比较的坑

    Java在处理Integer时使用了一个缓存,其中缓存了-128到127之间的数字对应的Integer对象,所以在绝大多数情况下,当我们把2个小于128的Integer对象用==比较时,Java往往是 ...

  7. The Preliminary Contest for ICPC Asia Xuzhou 2019 J Random Access Iterator (树形DP)

    每次循环向下寻找孩子时,随机选取一个孩子,设dp[u]为从u出发,不能得出正确答案的概率,则从u出发,走一次的情况下不能得出正确答案的概率是 P = (dp[v1]+dp[v2]+dp[v3]+--d ...

  8. 吴裕雄 python 机器学习——模型选择损失函数模型

    from sklearn.metrics import zero_one_loss,log_loss def test_zero_one_loss(): y_true=[1,1,1,1,1,0,0,0 ...

  9. ZooKeeper-集群模式配置

    (1)下载安装zookeeper,进行基本的配置,详细教程:https://www.cnblogs.com/excellencesy/p/11956485.html (2)在三台虚拟机上分别按照以上方 ...

  10. 再见2018,你好2019 -- 致 Mac 背后的自己

    转眼间 2018 年即将过去,心有万千感慨,真的感觉到时间如白驹过隙,成长没有跟上时间的脚步,这叫老了一岁,如果跟上了,那就叫成熟了一岁.很遗憾,2018年我老了一岁. 新年之初,立过好几个 Flag ...