[leetcode]65. Valid Number

链接:https://leetcode.com/problems/valid-number/description/

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.


这道题条条框框是在太多了,各种情况。。不过简略来说,正确的做法应该是:
1、熟悉数字的表述规则
2、对输入的数字首先进行必要的检测,是否有abc或者中间空格等非法字符
3、将e前面和e后面分开计算!e前面允许有小数点形式的,e后面不允许有小数点形式的
4、数字的形式一般是 可以有正负号,如果是0.几,可以省略0,“.”前面不一定有数字,点后面一定有数字。。等等

class Solution {
public:
    bool isNumber(string s) {
        while(!s.empty() && s[0]==' ') s.erase(s.begin());
        while(!s.empty() && s[s.size()-1]==' ') s.erase(s.end()-1);
        
        if(s.empty()) return false;
        
        if(s.find('e')==-1) return check(s,true);
        else return check(s.substr(0,s.find('e')),true) &&  check(s.substr(s.find('e')+1),false);
    }
    
    bool check(string s, bool point)
    {
        
        //为空肯定失败
        if(s.empty()) return false;
        int i=0;
        bool num=false;
        
        //是否存在符号,十号的话要先跳过,且只能有一个。。如果符号过后就没有数字了,那么也是非法的
        if(s[i]=='+' || s[i]=='-') i++;
        if(i==s.size()) return false;
        
        //整数位置的数据
        while(i<s.length() && s[i]<='9' && s[i]>='0')
        {
            i++;
            num=true;
        }
        
        //如果不允许出现小数点,那么这个过程就必须匹配结束,不然就是失败
        if(i<s.size() && point==false)
            return false;
        
         //允许小数点,下一位必须为小数点
         //小数点后,必须遇到e或结束
        if(i<s.size() && s[i]=='.')
        {
            bool num2=false;
            i++;
            while(i<s.size() && s[i]<='9' && s[i]>='0')
            {
                i++;
                num2=true;
            }
            if(num2==false && num==false)
                return false;
        }
        return i==s.size();

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值