LeetcodeMedium-【面試題20. 表示數值的字符串】

請實現一個函數用來判斷字符串是否表示數值(包括整數和小數)。例如,字符串"+100"、“5e2”、"-123"、“3.1416”、“0123"及”-1E-16"都表示數值,但"12e"、“1a3.14”、“1.2.3”、"±5"及"12e+5.4"都不是。

注意:本題與主站 65 題相同:https://leetcode-cn.com/problems/valid-number/

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路1:直接判斷

先利用e進行切割,然後反別判斷底數部分是否是一個數字(包含整數和小數),判斷指數部分是否存在且是否爲整數。
此外題目應該描述有問題:E應該是不合法的,"-1E-16"是爲False。
在這裏插入圖片描述

class Solution:
    def isNumber(self, s: str) -> bool:
        # 判斷是不是數值:
        def isnum(s) ->bool:
            if s == '':
                return False
            if s[0] == '-' or s[0] == '+':
                s = s[1:]
            if len(s) == 0:
                return False
            f = 0
            c = 0
            for i in range(len(s)):
                if s[i] >= '0' and s[i] <= '9':
                    c = 1
                    continue
                if f == 0 and s[i] == '.':
                    f = 1
                    continue
                return False
            return True and c == 1
        # 判斷是不是整數
        def isnum2(s) -> bool:
            if s == '':
                return False
            if s[0] == '-' or s[0] == '+':
                s = s[1:]
            if s == '':
                return False
            for i in range(len(s)):
                if s[i] >= '0' and s[i] <= '9':
                    continue
                else:
                    return False
            return True
        # s = s.lower()
        sList = s.strip().split('e')
        b1 = isnum(sList[0]) # 去掉首尾空格
        b2 = True
        if len(sList) == 2:
            b2 = isnum2(sList[1])
        elif len(sList) > 2:
            return False
        return b1 and b2 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章