驗證給定字符串是否為合法數字。例子:
"0" → true" 0.1 " → true"abc" → false"1 a" → false"2e10" → true題目描述故意模糊,需自行總結所有規則再實現。
將字符分為 6 類輸入:
| 類型 | 代碼 | 包含字符 |
|---|---|---|
| INVALID | 0 | 字母、括號、& 等非法字符 |
| SPACE | 1 | 空格 |
| SIGN | 2 | +、- |
| DIGIT | 3 | 0-9 |
| DOT | 4 | . |
| EXPONENT | 5 | e、E |
定義 9 個狀態:
..e/Ee 後讀符號e 後讀數字狀態轉移表(-1 表示非法):
// 輸入: INV SPA SIG DIG DOT EXP
int transTable[9][6] = {
{-1, 0, 3, 1, 2, -1}, // 0
{-1, 8, -1, 1, 4, 5}, // 1
{-1, -1, -1, 4, -1, -1}, // 2
{-1, -1, -1, 1, 2, -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
};
接受狀態:1, 4, 7, 8
class Solution {
public:
bool isNumber(const char *s) {
enum InputType { INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT };
int transTable[9][6] = {
{-1, 0, 3, 1, 2, -1},
{-1, 8, -1, 1, 4, 5},
{-1, -1, -1, 4, -1, -1},
{-1, -1, -1, 1, 2, -1},
{-1, 8, -1, 4, -1, 5},
{-1, -1, 6, 7, -1, -1},
{-1, -1, -1, 7, -1, -1},
{-1, 8, -1, 7, -1, -1},
{-1, 8, -1, -1, -1, -1}
};
int state = 0;
while (*s) {
InputType input = INVALID;
if (*s == ' ') input = SPACE;
else if (*s == '+' || *s == '-') input = SIGN;
else if (isdigit(*s)) input = DIGIT;
else if (*s == '.') input = DOT;
else if (*s == 'e' || *s == 'E') input = EXPONENT;
state = transTable[state][input];
if (state == -1) return false;
++s;
}
return state == 1 || state == 4 || state == 7 || state == 8;
}
};
if-else 地獄