算法-leetcode-65-Valid Number
算法-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的更多相关文章
- [leetcode]65. Valid Number 有效数值
Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...
- leetCode 65.Valid Number (有效数字)
Valid Number Validate if a given string is numeric. Some examples: "0" => true " ...
- [LeetCode] 65. Valid Number 验证数字
Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...
- LeetCode 65 Valid Number
(在队友怂恿下写了LeetCode上的一个水题) 传送门 Validate if a given string is numeric. Some examples: "0" =&g ...
- Leetcode 65 Valid Number 字符串处理
由于老是更新简单题,我已经醉了,所以今天直接上一道通过率最低的题. 题意:判断字符串是否是一个合法的数字 定义有符号的数字是(n),无符号的数字是(un),有符号的兼容无符号的 合法的数字只有下列几种 ...
- [LeetCode] 65. Valid Number(多个标志位)
[思路]该题题干不是很明确,只能根据用例来理解什么样的字符串才是符合题意的,本题关键在于几个标志位的设立,将字符串分为几个部分,代码如下: class Solution { public: strin ...
- 【LeetCode】65. Valid Number
Difficulty: Hard More:[目录]LeetCode Java实现 Description Validate if a given string can be interpreted ...
- 【leetcode】Valid Number
Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...
- 【一天一道LeetCode】#65. Valid Number
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Validat ...
- 65. Valid Number
题目: Validate if a given string is numeric. Some examples:"0" => true" 0.1 " = ...
随机推荐
- 吴裕雄 python 机器学习——集成学习随机森林RandomForestClassifier分类模型
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets,ensemble from sklear ...
- 查看Mysql数据库版本
一.使用终端 1.参数为-V(大写字母)或者--version 使用方法: D:\mysql\bin>mysql -V 或者 D:\mysql\bin>mysql --version
- VS常用快捷键(2012)
Ctrl+K,D ----格式化全部代码 Ctrl+K,F ----格式化选中的代码 Ctrl+K,C ----注释选定内容 Ctrl+K,U ----取消注释选定内容 Ctrl+J或者 Ctrl+S ...
- javascript 删除对象的属性 delete
1.当属性存在 configurable:true delete命令会返回true var obj={a:1}; delete obj.a //true console.log(obj);//{} 2 ...
- 小杨排队(dp)
链接:https://ac.nowcoder.com/acm/contest/3667/J 题目描述 小阳想要买个东西,然后就去了商店,发现进商店需要排队(生意太火爆!),然后就开始漫长的等待,他觉得 ...
- 基于SILVACO ATLAS的a-IGZO薄膜晶体管二维器件仿真(07)
今天主要解决一下defect语句: defect region=1 nta=1.55e20 wta=0.013 wtd=0.12 ngd=6.5e16 wga=2 ntd=1.55e20 ngd=0 ...
- call深入理解
function fn1() { console.log(1); } function fn2() { console.log(2); } fn1.call(fn2); // 1 fn1.call.c ...
- echart 重新加载
myechart2.clear(); myechart2.setOption(options[1]);
- JS-防抖与节流
问题的由来:一些事件频繁的被触发而导致频繁的调用事件处理程序,从而造成程序不必要的开销,影响程序性能:防抖和节流就是为了解决这种情况造成的性能消耗. 场景1:使用keyup事件监听输入框的值进行请求搜 ...
- 批量导出存储在msdb库的SSIS包
http://blog.51cto.com/ultrasql/1924464 use msdb go IF OBJECT_ID('msdb.dbo.usp_ExportSSISPkgs') IS NO ...