[LeetCode] Valid Number
Valid Number
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.
解题思路:
这道题其实并不难,主要是理解题意,且弄清楚double类型的各中情况。对于含e的double类型,e左边必须是浮点类型,右边必须是整型,且不能为空。还有一种情况就是两边可能有空格,这道题认为也是正确的,因此我的代码里面加上了一个trim函数。另外,不考虑大写的E,其实应该考虑的。
我的思路很简单,分有e跟无e两种情况讨论。注意c++的string类型中是find来查找,而不是indexof。
下面是代码:
class Solution { public: bool isNumber(string s) { //s = s.tolower(); s = trim(s); int eIndex = s.find('e'); if(eIndex == s.length() - 1){ return false; } else if(eIndex < 0){ return isDouble(s); }else{ return isDouble(s.substr(0, eIndex))&&isInt(s.substr(eIndex + 1)); } } private: bool isDouble(string s){ int len = s.length(); if(len == 0){ return false; } //符号位 if(s[0] == '+' || s[0] == '-'){ s = s.substr(1); len--; if(len==0){ return false; } } //只有一个小数点的情况 if(s[0]=='.'&&len==1){ return false; } int dotIndex = -1; //小数点的下标 for(int i = 0; i<len; i++){ if(s[i]=='.'){ if(dotIndex>=0){ //已经有小数点了 return false; }else{ dotIndex = i; } }else if(s[i]<'0'||s[i]>'9'){ return false; } } } bool isInt(string s){ //符号位 int len = s.length(); if(len == 0){ return false; } if(s[0] == '+' || s[0] == '-'){ s = s.substr(1); len--; if(len==0){ return false; } } for(int i=0; i<len; i++){ if(s[i]>'9'||s[i]<'0'){ return false; } } return true; } string trim(string s){ int len = s.length(); int l = 0,r = len - 1; //s左右第一个非空字符的位置 while(l<len){ if(s[l]==' '|| s[l] == '\t' || s[l]=='\r' || s[l]=='\n'){ l++; continue; } break; } while(r>=0){ if(s[r]==' '|| s[r] == '\t' || s[r]=='\r' || s[r]=='\n'){ r--; continue; } break; } s = s.substr(l, r - l +1); return s; } };
0 条评论