解法一:逐位判断+标记法
Java
class Solution {
public boolean isNumber(String s) {
if(s == null || s.length() == 0) return false;
boolean isNum = false, isDot = false, ise_or_E = false;
char[] str = s.trim().toCharArray();
for(int i=0; i<str.length; i++) {
if(str[i] >= '0' && str[i] <= '9') isNum = true;
else if(str[i] == '.') {
if(isDot || ise_or_E) return false;
isDot = true;
}
else if(str[i] == 'e' || str[i] == 'E') {
if(!isNum || ise_or_E) return false;
ise_or_E = true;
isNum = false;
}
else if(str[i] == '-' ||str[i] == '+') {
if(i!=0 && str[i-1] != 'e' && str[i-1] != 'E') return false;
}
else return false;
}
return isNum;
}
}
Python
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0: return False
s = s.strip()
isNum, isDot, is_eorE = False, False, False
for i in range(len(s)):
if s[i].isdigit(): isNum = True
elif s[i] == '.':
if isDot or is_eorE: return False
isDot = True
elif s[i] == 'e' or s[i] == 'E':
if not isNum or is_eorE: return False
is_eorE = True
isNum = False
elif s[i] == '+' or s[i] == '-':
if i != 0 and s[i-1] != 'e' and s[i-1] != 'E': return False
else: return False
return isNum
解法二:有限状态自动机
详细题解参考