题目:
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.
思路:
这种题目没有什么算法可言,完全考察的是对corner case的考虑是否完全。下面代码在注释中给出了处理各种corner case的情况。其基本思路如下:设置一个索引计数器,判断走到了字符串的哪个位置;再设置一个digit计数器,判断某些部分的digit的个数是否合法。然后就是一步步从前往后走了,一旦遇到非法情况就返回false。等到一直走到末尾的时候还没发现非法情况,就返回true。
代码:
class Solution {
public:
bool isNumber(string s) {
int i = 0; // the index
int k = 0; // the count for digits
int len = s.size();
while (s[i] == ' ') ++i; // remove prefix ' '
if (s[i] == '+' || s[i] == '-') ++i; // tackle the sign part
while (isdigit(s[i])) ++i, ++k; // the integer part
if(s[i] == '.') ++i; // the seperator
while (isdigit(s[i])) ++i, ++k; // the fraction part
if (k == 0) return false; // no digits found
if (s[i] == 'e' || s[i] == 'E') { // same as integer part
++i, k = 0;
if(s[i] == '+' || s[i] == '-') ++i;
while(isdigit(s[i])) ++i, ++k;
if(k == 0) return false;
}
while (s[i] == ' ') ++i; // remove the suffix
return i == len;
}
};
Follow Up:
如果不仅仅是判断合法性,而是要求将一个字符串转换成为一个double类型的数据呢?其实Leetcode上面也有完全类似的题目,可以参考,会发现两者的代码非常类似。不过在面试的时候,最好和面试官讨论各种情况,例如如果溢出呢?其它各种特殊情况如何处理?