Valid Number(Hard)
题目描述
Validate if a given string is numeric.
Example
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
题目链接
解题思路
给几组比较容易漏掉的例子:
- "e" => false
- "." => false
- "1 " => false
- "+.8" => true
- " " => false
- "54 aa" => false
参考程序
class Solution {
public:
/**
* @param s the string that represents a number
* @return whether the string is a valid number
*/
bool isNumber(string& t) {
// Write your code her
string s = "";
int i = 0, m = t.length();
while (i < m && t[i] == ' ') ++ i;
if (i >= m) return false;
while (i < m && t[i] != ' ') s.push_back(t[i ++]);
while (i < m && t[i] == ' ') ++ i;
if (i < m) return false;
for (char ch: s) if (ch != '+' && ch != '-' && ch != '.' && ch != 'e' && !isdigit(ch)) return false;
int cnt_e = 0, cnt_dot = 0;
for (char ch: s) {
if (ch == 'e') ++ cnt_e;
else if (ch == '.') {
++ cnt_dot;
}
}
if (cnt_e > 1 || cnt_dot > 1) return false;
int n = s.length();
bool has_e = false;
for (int i = 0; i < n; ++ i) {
if (s[i] == 'e') {
if (i == 0) return false;
else if (i == 1 && s[i - 1] == '.') return false;
has_e = true;
} else if (s[i] == '.' ) {
if (has_e) return false;
bool flag = false;
if (i > 0 && isdigit(s[i - 1])) flag = true;
if (i < n - 1 && isdigit(s[i + 1])) flag = true;
if (flag == false) return false;
}
}
return true;
}
};