劍指offer:表示數值的字串(Python)
阿新 • • 發佈:2019-02-09
題目描述
請實現一個函式用來判斷字串是否表示數值(包括整數和小數)。例如,字串”+100”,”5e2”,”-123”,”3.1416”和”-1E-16”都表示數值。 但是”12e”,”1a3.14”,”1.2.3”,”+-5”和”12e+4.3”都不是。
解題思路
定義兩個標誌位,分別表示E
或者e
是否出現過,以及小數點.
是否出現過。
1. 以e
(或E
)為分隔,獲得兩個子字串;e
之前的字串小數點只能出現一次;e
之後的字串不允許出現小數點;
2. 符號位+
或-
只可能出現在兩個子字串的首位;
3. e
(或E
)、小數點.
不能出現在末尾
這種思路下的程式碼毫無技術含量,看著自己寫的程式碼實在有些不忍猝讀。先貼在這裡,期待後續溫故時的更好解法。
def isNumeric(self, s):
isAllowDot = True
isAllowE = True
for i in range(len(s)):
if s[i] in "+-" and (i==0 or s[i-1] in "eE") and i < len(s)-1:
continue
elif isAllowDot and s[i] == ".":
isAllowDot = False
if i >= len(s)-1 or s[i+1 ] not in "0123456789":
return False
elif isAllowE and s[i] in "Ee":
isAllowDot = False
isAllowE = False
if i >= len(s)-1 or s[i+1] not in "0123456789+-":
return False
elif s[i] not in "0123456789":
return False
return True