剑指 Offer 20 表示数值的字符串
概述
https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
解法
虽然我写过解释器吧,但是还是忽视了两点:
- 需要检查 dot 是否二次出现;
- 符号过后,下一个不为 . 时,其必须是数字;
class Solution {
public:
int i = 0;
bool isNumber(string s) {
s.push_back('\0');
while (s[i] == ' ') i ++;
if (s[i] == '\0') return false;
if (s[i] == '+' || s[i] == '-') i ++;
if (s[i] == '\0') return false;
bool dot = false;
if (s[i] == '.') {
dot = true;
i ++;
if (!isdigit(s[i])) return false;
i ++;
} else {
if (!isdigit(s[i])) return false;
}
while (isdigit(s[i])) i ++;
if (s[i] == '.') {
if (dot) return false;
i ++;
while (isdigit(s[i])) i ++;
}
if (s[i] == 'e' || s[i] == 'E') {
i ++;
if (s[i] == '+' || s[i] == '-') i ++;
if (!isdigit(s[i])) return false;
while (isdigit(s[i])) i ++;
}
while (i < s.size() - 1) {
if (s[i] != ' ') return false;
i ++;
}
return true;
}
};
Links: sword-offer-20