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;}};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值