1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Jan 25, 2015
4
+ Problem: Valid Number
5
+ Difficulty: Hard
6
+ Source: https://oj.leetcode.com/problems/valid-number/
7
+ Notes:
8
+ Validate if a given string is numeric.
9
+ Some examples:
10
+ "0" => true
11
+ " 0.1 " => true
12
+ "abc" => false
13
+ "1 a" => false
14
+ "2e10" => true
15
+ Note: It is intended for the problem statement to be ambiguous. You should gather all
16
+ requirements up front before implementing one.
17
+
18
+ Solution: This finite-state machine solution. Learn from fuwutu & snakeDling.
19
+ */
20
+
21
+ public class Solution {
22
+ public boolean isNumber (String s ) {
23
+ int start = 0 , end = s .length () -1 ;
24
+ boolean dot = false , exp = false , digit = false ;
25
+ while (start <= end && (s .charAt (start ) == ' ' )) ++start ;
26
+ while (start <= end && (s .charAt (end ) == ' ' )) --end ;
27
+ if (start <= end && (s .charAt (start ) == '+' || s .charAt (start ) == '-' )) ++start ;
28
+ if (start > end ) return false ;
29
+ for ( ; start <= end ; ++start ) {
30
+ if (Character .isDigit (s .charAt (start ))) digit = true ;
31
+ else if (s .charAt (start ) == 'e' || s .charAt (start ) == 'E' ) {
32
+ if (exp == true || digit == false || start == end ) return false ;
33
+ exp = true ;
34
+ } else if (s .charAt (start ) == '.' ) {
35
+ if (dot == true || exp == true ) return false ;
36
+ if (digit == false && start == end ) return false ;
37
+ dot = true ;
38
+ } else if (s .charAt (start ) == '+' || s .charAt (start ) == '-' ) {
39
+ if (start == end ) return false ;
40
+ if (s .charAt (start -1 ) != 'e' && s .charAt (start -1 ) != 'E' ) return false ;
41
+ } else return false ;
42
+ }
43
+ return true ;
44
+ }
45
+ }
0 commit comments