验证给定的字符串是否为数字。
例如: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。
这其实就是一个自动状态机的问题
状态转换图
boolean numBeforeE = false;
boolean numAfterE = false;
numBeforeE && Arrays.asList(2, 3, 4).contains(state) || numBeforeE && numAfterE;
public boolean isNumber(String s) {
s = s.trim().toLowerCase();
// use a flag for deciding on dot
boolean numBeforeE = false;
boolean numAfterE = false;
int state = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
// state transition
if (state <= 2) state = 2;
else if (state <= 4) state = 4;
else if (state <= 7) state = 7;
else return false;
// update num flag
if (state <= 4) numBeforeE = true;
if (state > 4) numAfterE = true;
} else if (ch == '+' || ch == '-') {
// state transition
if (state == 0 || state == 5) state++;
else return false;
} else if (ch == '.') {
if (state <= 2) state = 3;
else return false;
} else if (ch == 'e') {
if (2 <= state && state <= 4) state = 5;
else return false;
} else {
return false;
}
}
return numBeforeE && Arrays.asList(2, 3, 4).contains(state) || numBeforeE && numAfterE;
}
本文分享自 Leetcode名企之路 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!