|
@@ -0,0 +1,58 @@
|
|
|
+class Solution {
|
|
|
+ // Numbers 0-9
|
|
|
+ // Exponent - "e"
|
|
|
+ // Positive/negative sign - "+"/"-"
|
|
|
+ // Decimal point - "."
|
|
|
+ public boolean isNumber(String s) {
|
|
|
+ // Finite automaton
|
|
|
+ // State No. | Discription
|
|
|
+ // -1 | Invalid state
|
|
|
+ // 0 | Initail state
|
|
|
+ // 1 | Input sign
|
|
|
+ // 2 | Input digit
|
|
|
+ // 3 | Input dot
|
|
|
+ // 4 | Input digit and dot
|
|
|
+ // 5 | Input exp
|
|
|
+ // 6 | Input sign after exp
|
|
|
+ // 7 | Input digit after exp
|
|
|
+ // 8 | Input space after valid number
|
|
|
+ // Input state:
|
|
|
+ // INVALID, SPACE, SIGN, DIGIT, DOT, EXP
|
|
|
+ // Trans table:
|
|
|
+ // input ERR SPA SGN DIG DOT EXP
|
|
|
+ // state
|
|
|
+ // 0 -1 0 1 2 3 -1
|
|
|
+ // 1 -1 -1 -1 2 3 -1
|
|
|
+ // 2 -1 8 -1 2 3 5
|
|
|
+ // 3 -1 -1 -1 4 -1 5
|
|
|
+ // 4 -1 8 -1 4 -1 5
|
|
|
+ // 5 -1 -1 6 7 -1 -1
|
|
|
+ // 6 -1 -1 -1 7 -1 -1
|
|
|
+ // 7 -1 8 -1 7 -1 -1
|
|
|
+ // 8 -1 8 -1 -1 -1 -1
|
|
|
+ char[] num = s.toCharArray();
|
|
|
+ int[][] stateTable = new int[][] {
|
|
|
+ {-1, 0, 1, 2, 3, -1}, // 0
|
|
|
+ {-1, -1, -1, 2, 3, -1}, // 1
|
|
|
+ {-1, 8, -1, 2, 4, 5}, // 2
|
|
|
+ {-1, -1, -1, 4, -1, -1}, // 3
|
|
|
+ {-1, 8, -1, 4, -1, 5}, // 4
|
|
|
+ {-1, -1, 6, 7, -1, -1}, // 5
|
|
|
+ {-1, -1, -1, 7, -1, -1}, // 6
|
|
|
+ {-1, 8, -1, 7, -1, -1}, // 7
|
|
|
+ {-1, 8, -1, -1, -1, -1} // 8
|
|
|
+ };
|
|
|
+ int state = 0;
|
|
|
+ for (int i = 0; i < num.length; i++) {
|
|
|
+ int input = 0;
|
|
|
+ if (num[i] == ' ') input = 1;
|
|
|
+ else if (num[i] == '+' || num[i] == '-') input = 2;
|
|
|
+ else if ('0' <= num[i] && num[i] <= '9') input = 3;
|
|
|
+ else if (num[i] == '.') input = 4;
|
|
|
+ else if (num[i] == 'e' || num[i] == 'E') input = 5;
|
|
|
+ state = stateTable[state][input];
|
|
|
+ if (state == -1) return false;
|
|
|
+ }
|
|
|
+ return state == 2 || state == 4 || state == 7 || state == 8;
|
|
|
+ }
|
|
|
+}
|