Skip to content

Commit b6d46e0

Browse files
committed
finish 65
1 parent c674b5f commit b6d46e0

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

65. Valid Number.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* 65. Valid Number
3+
*
4+
* Validate if a given string is numeric.
5+
*
6+
* Some examples:
7+
* "0" => true
8+
* " 0.1 " => true
9+
* "abc" => false
10+
* "1 a" => false
11+
* "2e10" => true
12+
*
13+
* Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
14+
*
15+
* Update (2015-02-10):
16+
* 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.
17+
*/
18+
19+
/**
20+
* @param {string} s
21+
* @return {boolean}
22+
*/
23+
var isNumber = function(s) {
24+
var state = [
25+
{},
26+
{'blank': 1, 'sign': 2, 'digit':3, '.':4},
27+
{'digit':3, '.':4},
28+
{'digit':3, '.':5, 'e':6, 'blank':9},
29+
{'digit':5},
30+
{'digit':5, 'e':6, 'blank':9},
31+
{'sign':7, 'digit':8},
32+
{'digit':8},
33+
{'digit':8, 'blank':9},
34+
{'blank':9}
35+
];
36+
var validState = [3, 5, 8, 9];
37+
var currentState = 1;
38+
var len = s.length;
39+
var str = '';
40+
var type = '';
41+
for (var i = 0; i < len; i++) {
42+
str = s[i];
43+
if (str >= '0' && str <= '9') {
44+
type = 'digit';
45+
} else if (str === '+' || str === '-') {
46+
type = 'sign';
47+
} else if (str === ' ') {
48+
type = 'blank';
49+
} else {
50+
type = str;
51+
}
52+
if (state[currentState][type] === undefined) {
53+
return false;
54+
} else {
55+
currentState = state[currentState][type];
56+
}
57+
}
58+
if (validState.indexOf(currentState) === -1) {
59+
return false;
60+
} else {
61+
return true;
62+
}
63+
};
64+
65+
// DFA 确定有限状态自动机
66+
// https://leetcode.com/problems/valid-number/discuss/23728/A-simple-solution-in-Python-based-on-DFA

0 commit comments

Comments
 (0)