description:
65 | Valid Number | 12.7% | Hard |
Validate if a given string is numeric.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
my solution:
class Solution {
public:
bool isNumber(string s) {
int flagE = 0;
int posE = 0;
int posPoint = 0;
int flagPoint = 0;
int flagSpace = 0;
int flagFront = 0;
int flagBack = 0;
int i = 0;
while (isspace(s[i])) i++;
if (i == s.length()) return false;
if (s[i] == '+' || s[i] == '-') i++; // check for sign
for (; i != s.length(); i++) {
if (s[i] == '.') {
flagPoint++;
posPoint = i;
if (flagPoint > 1) return false;
}
else if (isspace(s[i])) {
flagSpace++;
break;
}
else if (!isdigit(s[i]) && !isspace(s[i])) {
if (s[i] == 'e' || s[i] == 'E') {
posE = i;
flagE++;
if (flagE > 1) return false;
if (s[i + 1] == '+' || s[i + 1] == '-') i++; //check for sign
}
else return false;
}
}
if (flagSpace != 0) {
for (; i != s.length(); i++) {
if (!isspace(s[i])) return false;
}
}
if (flagE == 1 && flagPoint == 1) {
if (posE < posPoint) return false;
}
if (flagE == 1) {
i = posE - 1 > -1 ? posE - 1 : 0;
while (!isdigit(s[i])) {
i--;
if (i == -1) return false;
}
i = posE + 1 < s.length() ? posE + 1 : s.length() - 1;
while (!isdigit(s[i])) {
i++;
if (i == s.length()) return false;
}
}
if (flagPoint == 1) {
i = posPoint - 1 > -1 ? posPoint - 1 : 0;
while (!isdigit(s[i])) {
i--;
if (i == -1) flagFront = 1;
}
i = posPoint + 1 < s.length() ? posPoint + 1 : s.length() - 1;
while (!isdigit(s[i])) {
i++;
if (i == s.length()) flagBack = 1;
}
if (flagBack == 1 && flagFront == 1) return false;
}
return true;
}
};
better ways:
by yangf0722
class Solution {
public:
bool isNumber(string str) {
int state=0, flag=0; // flag to judge the special case "."
while(str[0]==' ') str.erase(0,1);//delete the prefix whitespace
while(str[str.length()-1]==' ') str.erase(str.length()-1, 1);//delete the suffix whitespace
for(int i=0; i<str.length(); i++){
if('0'<=str[i] && str[i]<='9'){
flag=1;
if(state<=2) state=2;
else state=(state<=5)?5:7;
}
else if('+'==str[i] || '-'==str[i]){
if(state==0 || state==3) state++;
else return false;
}
else if('.'==str[i]){
if(state<=2) state=6;
else return false;
}
else if('e'==str[i]){
if(flag&&(state==2 || state==6 || state==7)) state=3;
else return false;
}
else return false;
}
return (state==2 || state==5 || (flag&&state==6) || state==7);
}
};
thought:
提交了12次终于过了,这道题其实算法并不难,但是对细心程度的要求比较高,需要考虑到每一种情况。
全而不漏感觉需要从最基础的开始考虑,比如从{[0-9]|.|*}+开始考虑,并且还要熟悉科学计数法的定义。