代码改变世界

[LeetCode 65] Valid Number (有效数字表达)

2017-11-17 02:35  naturesound  阅读(476)  评论(0编辑  收藏  举报

 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:

如 - 4.5e2, 5.3e, 4e4.6, +e9, e5, 4.9 e1等等都是错误的。

各种if条件判断很扰人,但其实如果把这个数字分为e之前和之后两部分来分别考虑会简化不少,也容易实现,直接将难度从Hard降为Medium.

把各种情况概况起来就是:

1)出现在e之前的应该为一个有效的浮点数,e之后的应该为有效整数。

2)有效浮点数规则:a)正负号只能出现在最前面;b)小数点只有一个; c)中间不能出现其他非数字字符; d)至少有一个数字

3)有效整数规则:    a)正负号只能出现在最前面;b)没有小数点;        c)中间不能出现其他非数字字符; d)至少有一个数字

class Solution {
public:
    bool isNumber(string s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ")+1);
        int pos = s.find_first_of("e");
        if(pos == -1) return isValidfloat(s);
        else return isValidfloat(s.substr(0, pos)) && isValidInteger(s.substr(pos+1));
    }
    bool isValidfloat(string s){
        if(!s.empty() && (s[0] == '-' || s[0] == '+')) s.erase(s.begin());
        int n_dot = 0;
        for(int i=0; i<s.size(); i++){
            if(s[i] == '.') n_dot++;
            else if(!isdigit(s[i])) return false;
        }
        return n_dot <= 1 && s.size() > n_dot;
    }
    bool isValidInteger(string s){
        if(!s.empty() && (s[0] == '-' || s[0] == '+')) s.erase(s.begin());
        for(int i=0; i<s.size(); i++){
            if(!isdigit(s[i])) return false;
        }
        return s.size();
    }
    
};
View Code