程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode Valid Number

LeetCode Valid Number

編輯:C++入門知識

LeetCode Valid Number


LeetCode解題之Valid Number


原題

判斷一個字符串是否是數值類型的。這裡的數值類型除了一般要考慮的小數、正負數外還要考慮科學計數法e,如” -3.2e-23 “是數值類型的。

注意點:

小數點前和後沒有數字都是合法的 科學計數法後面也可以是負數

例子:

輸入: s = ” -3.2e-23 “

輸出: True

解題思路

比較惡心的一道題,沒有明確給出定義,給了一些例子,需要自己不斷去嘗試。首先要把前後的空字符給去掉。然後依次考慮符號、數字、小數點、數字,如果有這些中連續的幾個,表示目前是一個普通的數值。繼續判斷”e”(注意大小寫都可以),接著判斷符號、數字,如果e後面沒有數字,那麼這是一個不正常的科學類數值。最後根據三種情況來綜合判斷,要滿足目標是一個數值類型,那麼首先要保證e前面的數是正常的,如果有e的話,要保證它後面的數也是正常的,最後要保證整個字符串都已經遍歷玩了,如果沒有說明中間出現了一些異常的字符或者末尾多了一些多余的字符。

AC源碼

class Solution(object):
    def isNumber(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s = s.strip()
        length = len(s)
        index = 0
        # Deal with symbol
        if index < length and (s[index] == '+' or s[index] == '-'):
            index += 1
        is_normal = False
        is_exp = True
        # Deal with digits in the front
        while index < length and s[index].isdigit():
            is_normal = True
            index += 1
        # Deal with dot ant digits behind it
        if index < length and s[index] == '.':
            index += 1
            while index < length and s[index].isdigit():
                is_normal = True
                index += 1
        # Deal with 'e' and number behind it
        if is_normal and index < length and (s[index] == 'e' or s[index] == 'E'):
            index += 1
            is_exp = False
            if index < length and (s[index] == '+' or s[index] == '-'):
                index += 1
            while index < length and s[index].isdigit():
                index += 1
                is_exp = True
        # Return true only deal with all the characters and the part in front of and behind 'e' are all ok
        return is_normal and is_exp and index == length


if __name__ == "__main__":
    assert Solution().isNumber("3.e-23") == True
    assert Solution().isNumber(".2e81") == True
    assert Solution().isNumber("2e10") == True
    assert Solution().isNumber(" 0.1") == True
    assert Solution().isNumber("1 b") == False
    assert Solution().isNumber("3-2") == False
    assert Solution().isNumber("abc") == False

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved