--- title: 【LeetCode】0065. Valid Number date: 2019-01-04 is_modified: false disqus: cynthiahackmd categories: - "面試刷題" tags: - "LeetCode" --- {%hackmd @CynthiaChuang/Github-Page-Theme %} <br> Validate if a given string can be interpreted as a decimal number. <!--more--> Some examples: ```python "0" => True " 0.1 " => True "abc" => False "1 a" => False "2e10" => True " -90e3 " => True " 1e" => False "e3" => False " 6e-1" => True " 99e2.5 " => False "53.5e93" => True " --6 " => False "-+3" => False "95a54e53" => False ``` <br><br> > **Note:** It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: > > - Numbers 0-9 > - Exponent - "e" > - Positive/negative sign - "+"/"-" > - Decimal point - "." > > Of course, the context of these characters also matters in the input. <br> **Related Topics:** `String`、`Math` ## 解題邏輯與實作 這題是要判斷給定的字串是否為一個合法的十進位數字,合法的數字中包含正負號、小數、科學記號 e,另外科學表示的部份 e 與後面的數字間可夾正號,最後是字串前後的的空白不影響判定。 基本上判定規則就這些,但需要特別注意兩個 case:`".1"` 與 `"3."` ,這兩種表示法也是合法的。 ### 正規表示式 Regular Expression 這種抽 pattern 的問題,我第一個想到的是 Regular Expression,思考會比簡單,程式碼也簡潔許多。 ```python= import re class Solution: def isNumber(self, s): reg = re.compile(r'^\s*[-+]?(\d+\.?|\.\d+)\d*(e[-+]?\d+)?\s*$') return re.match(reg, s) != None ``` ## 其他連結 1. [【LeetCode】0000. 解題目錄](/x62skqpKStKMxRepJ6iqQQ) <br><br> > **本文作者**: 辛西亞.Cynthia > **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/LeetCode-0065-Valid-Number) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/LeetCode-0065-Valid-Number) > **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up