|
| 1 | +# 65. Valid Number |
| 2 | + |
| 3 | +- Difficulty: Hard. |
| 4 | +- Related Topics: Math, String. |
| 5 | +- Similar Questions: String to Integer (atoi). |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Validate if a given string is numeric. |
| 10 | + |
| 11 | +Some examples: |
| 12 | +```"0"``` => ```true``` |
| 13 | +```" 0.1 "``` => ```true``` |
| 14 | +```"abc"``` => ```false``` |
| 15 | +```"1 a"``` => ```false``` |
| 16 | +```"2e10"``` => ```true``` |
| 17 | + |
| 18 | +**Note:** It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. |
| 19 | + |
| 20 | +**Update (2015-02-10):** |
| 21 | +The signature of the ```C++``` function had been updated. If you still see your function signature accepts a ```const char *``` argument, please click the reload button to reset your code definition. |
| 22 | + |
| 23 | +## Solution |
| 24 | + |
| 25 | +```javascript |
| 26 | +/** |
| 27 | + * @param {string} s |
| 28 | + * @return {boolean} |
| 29 | + */ |
| 30 | +var isNumber = function(s) { |
| 31 | + var state = [ |
| 32 | + {}, |
| 33 | + {'blank': 1, 'sign': 2, 'digit':3, '.':4}, |
| 34 | + {'digit':3, '.':4}, |
| 35 | + {'digit':3, '.':5, 'e':6, 'blank':9}, |
| 36 | + {'digit':5}, |
| 37 | + {'digit':5, 'e':6, 'blank':9}, |
| 38 | + {'sign':7, 'digit':8}, |
| 39 | + {'digit':8}, |
| 40 | + {'digit':8, 'blank':9}, |
| 41 | + {'blank':9} |
| 42 | + ]; |
| 43 | + var validState = [3, 5, 8, 9]; |
| 44 | + var currentState = 1; |
| 45 | + var len = s.length; |
| 46 | + var str = ''; |
| 47 | + var type = ''; |
| 48 | + for (var i = 0; i < len; i++) { |
| 49 | + str = s[i]; |
| 50 | + if (str >= '0' && str <= '9') { |
| 51 | + type = 'digit'; |
| 52 | + } else if (str === '+' || str === '-') { |
| 53 | + type = 'sign'; |
| 54 | + } else if (str === ' ') { |
| 55 | + type = 'blank'; |
| 56 | + } else { |
| 57 | + type = str; |
| 58 | + } |
| 59 | + if (state[currentState][type] === undefined) { |
| 60 | + return false; |
| 61 | + } else { |
| 62 | + currentState = state[currentState][type]; |
| 63 | + } |
| 64 | + } |
| 65 | + if (validState.indexOf(currentState) === -1) { |
| 66 | + return false; |
| 67 | + } else { |
| 68 | + return true; |
| 69 | + } |
| 70 | +}; |
| 71 | +``` |
| 72 | + |
| 73 | +**Explain:** |
| 74 | + |
| 75 | +[DFA 确定有限状态自动机](https://leetcode.com/problems/valid-number/discuss/23728/A-simple-solution-in-Python-based-on-DFA) |
| 76 | + |
| 77 | +**Complexity:** |
| 78 | + |
| 79 | +* Time complexity : O(n). |
| 80 | +* Space complexity : O(1). |
0 commit comments