剑指 Offer 20. 表示数值的字符串
这道题采用状态机来做,状态机的最大难度就是写出对应的数组。
以后匹配字符格式的可以采用状态机来做。

开始状态为state=0,
本题要注意空格的情况,最后还可以有空格,也就是图中的状态3
代码如下:
class Solution {
public boolean isNumber(String s) {
int[][] stateTable = {
{0, 2, 1, 4, -1, -1},
{-1, 2, -1, 4, -1, -1},
{3, 2, -1, 6, 7, -1},
{3, -1, -1, -1, -1, -1},
{-1, 5, -1, -1, -1, -1},
{3, 5, -1, -1, 7, -1},
{3, 6, -1, -1, 7, -1},
{-1, 8, 9, -1, -1, -1},
{3, 8, -1, -1, -1, -1},
{-1, 8, -1, -1, -1, -1}
};
int state = 0;
List<Integer> legalState = new ArrayList<Integer>() {{
add(2);
add(3);
add(5);
add(8);
add(6);
}};
for (int i = 0; i < s.length(); i++) {
state = stateTable[state][getCol(s.charAt(i))];
if (state == -1) return false;
}
if (legalState.contains(state)) return true;
return false;
}
public int getCol(char c){
if (c=='+'||c=='-') return 2;
if (c>='0'&&c<='9') return 1;
if (c=='.') return 3;
if (c=='E'||c=='e') return 4;
if (c==' ') return 0;
return 5;
}
}
网友评论