标签:style blog color strong os for
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.
只需要考虑正负号,小数点,指数e符号,数字四种可能,除了它们之外的字符,程序返回false。
class Solution { public: bool isVaild(char c){ if(c==‘+‘ || c==‘-‘ || c == ‘.‘ || c==‘e‘ || c>=‘0‘&& c <= ‘9‘) return true; else return false; } bool isNumber(const char *s) { string str(s); bool res = false; size_t pos = str.find_first_not_of(" "); if(pos!=string::npos) str=str.substr(pos); //去掉前端空格 else str=""; pos = str.find_last_not_of(" "); str=str.substr(0,pos+1); //去掉后端空格 if(str == "") return res; bool hasSign = false, hasDot = false, hasExp = false, hasDigit = false; int len = str.length(); for(int i = 0 ; i < len ;++ i){ char ch = str[i]; if(!isVaild(ch)) return false; switch(ch){ case ‘+‘: case ‘-‘: //不在第一个或者e后面;在最后一个字符 if((i!=0 && str[i-1]!=‘e‘) || i== len-1) return false; else hasSign = true; break; case ‘.‘: //只有一个字符的情况;只有符号和点;在e和点之后 if(len == 1 || (len == 2 && hasSign) || hasExp || hasDot) return false; else hasDot = true; break; case ‘e‘: //出现在第一个或最后一个;前面没有数字;前面有e if(i == 0 || i == len-1 || !hasDigit || hasExp) return false; else hasExp = true; break; default: hasDigit = true; break; } } return true; } };
Leetcode Valid Number,布布扣,bubuko.com
标签:style blog color strong os for
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3822944.html