把一个valid number看做一个顺序序列,把各个关键位置应为状态,比如开始空白部分,符号后,整数部分,小数部分,指数部分等
状态转移是递增的,往下走不会回退。这种定义类似KMP和正则的NFA的状态定义,状态就是处在pattern中的位置。
下的程序有bug, "."会被当作valid,懒得改了,需要调整下有些状态定义,但是不出“状态就是pattern中的位置”
bool isNumber(string s) {
enum { EMPTY, AFTER_SIGN, IN_INTEGER, AFTER_INTEGER, AFTER_POINT, AFTER_POINT2, IN_FRACTION, AFTER_FRACTION, AFTER_E, AFTER_EXP_SIGN, IN_EXP_INTEGER, AFTER_EXP_INTEGER } state;
state = EMPTY;
for (char &c : s) {
if (c == ' ') {
if (state == IN_INTEGER || state == AFTER_INTEGER ) state = AFTER_INTEGER;
else if (state == AFTER_POINT) state = AFTER_POINT2;
else if (state == IN_EXP_INTEGER || state == AFTER_EXP_INTEGER) state = AFTER_EXP_INTEGER;
else if (state == IN_FRACTION) state = AFTER_FRACTION;
else if (state != EMPTY && state != AFTER_POINT2 && state != AFTER_FRACTION) return false;
}
else if (c == '+' || c == '-') {
if (state != EMPTY && state != AFTER_E) return false;
if (state == AFTER_E) state = AFTER_EXP_SIGN;
else state = AFTER_SIGN;
}
else if (isdigit(c)) {
if (state == AFTER_INTEGER || state == AFTER_POINT2) return false;
if (state == AFTER_POINT || state == IN_FRACTION) state = IN_FRACTION;
else if (state == AFTER_E) state = IN_EXP_INTEGER;
else state = IN_INTEGER;
}
else if (c == '.') {
if (state != IN_INTEGER && state != EMPTY && state != AFTER_SIGN) return false;
state = AFTER_POINT;
}
else if (c == 'e' || c == 'E') {
if (state != IN_FRACTION && state != IN_INTEGER && state != AFTER_POINT) return false;
state = AFTER_E;
}
else return false;
}
return state == IN_INTEGER || state == AFTER_INTEGER || state == AFTER_POINT || state == AFTER_POINT2
|| state == IN_FRACTION || state == AFTER_FRACTION|| state == IN_EXP_INTEGER || state == AFTER_EXP_INTEGER;
}
def isNumber(self, s):
i, n = 0, len(s)
while i < n and s[i]==' ': i += 1
if i < n and s[i] in '+-': i += 1
isNum = False
while i < n and s[i].isdigit():
i += 1
isNum = True
if i < n and s[i] =='.':
i += 1
while i < n and s[i].isdigit():
i += 1
isNum = True
if i < n and isNum and s[i] == 'e':
i += 1
isNum = False
if i < n and s[i] in '+-': i += 1
while i < n and s[i].isdigit():
i += 1
isNum = True
while i < n and s[i] == ' ': i += 1
return isNum and i == n