LeetCode65 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.
题源:here;完整实现:here
吐槽:
这道题,只能人肉设置判断,什么意思?就是你需要自己考虑各种情况而不能通过递推公式或递归进行判断,这是目前为止通过率最低的一道题:
这里写图片描述
所以在经过多次失败以后,我参考了别人的答案,当然从别人的答案也可以发掘一些简化这类问题的技巧:由粗到细,即将遇到的各种情况分层进行分析判断。
思路:
我们将遇到的字符分类,不同的字符进行不同的处理,代码如下:

class Solution {
public:
    bool isDigit(char s){
        return (s <= '9' && s >= '0');}

    bool isSpace(char s){
        return s == ' ';}

    bool isSignal(char s){
        return s == '+' || s == '-';}

    bool isE(char s){
        return s == 'e';}

    bool isDot(char s){
        return s == '.';}

    bool isNumber(string s) {
        bool hasDot = false, hasE = false;
        while (s.size() && isSpace(s[0])) s.erase(0, 1);
        if (!s.size()) return false;

        if (isSignal(s[0])) s.erase(0, 1);
        int idx = 0;
        while (idx < s.size()){
            if (isDot(s[idx])){
                if (hasDot || hasE) return false;
                if (idx == 0 && !isDigit(s[idx+1])) return false;
                hasDot = true; idx++; continue;}
            else if (isE(s[idx])){
                if (idx == 0 || hasE) return false;
                if (isSignal(s[++idx])) idx++;
                if (!isDigit(s[idx++])) return false;
                hasE = true; continue;}
            else if (isSpace(s[idx])){
                while (idx < s.size()){
                    if (!isSpace(s[idx])) return false;
                    idx++;}
                return true;}

            else if (!isDigit(s[idx++])) return false;}

        return true;}};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80934156