leetcode|Valid Number(65)

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.

         这首题的难度为difficult,说难也不难,可是难就在于,怎样判断它是否输入为数字串,需要考虑的输入除了题目给出的几种,还有" 12   ", "-1.2   ",“+.1”,“ e0”......

       此时,我们应该分析一下,对于所有的输入类型,进行一个非数字串的错误分析,如果分析不清楚,就有可能落掉情况或者代码冗长。

      首先,我们把能够出现在字符中的内容分为以下六类:空格、数字、+ (-)号、小数点、e、其它。这几种类型有不是在字符串的每个位置都可以出现的,有些只能出现在特定的位置。

例如:

  1. 空格可以出现在首尾;
  2. + (-)号只能出现在除空格的第一个位置或者e的后面;
  3. .的后面必须有数字,它的前面可以有数字或者是+(-)符号;
  4. e的前面和后面必须有数字;

其次,为了不落掉任何一个位置上的信息,我们可以从头到尾来分析每个位置上的元素(遇到确定非数字串的情况就结束),来判断错误的输入;

代码如下:

class Solution {
private:
    bool isSpace(char c){ return c==' ';}
    bool isSgn(char c){ return c=='+'||c=='-';}
    bool isDot(char c){ return c=='.';}
    bool isNum(char c){ return c<='9'&&c>='0';}
    bool isE(char c){ return c=='e'||c=='E';}

public:
    bool isNumber(string s) {
        int pos=0;
        bool haveNum = false;

        // Check all the prefix spaces
        while ( pos<s.size() && isSpace(s[pos]) ) pos++;

        // Check the next char if it's a +/- signal
        if ( pos<s.size() && isSgn(s[pos]) ) pos++;

        // Check the numbers before a dot '.'
        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

        // Check the dot '.'
        if ( pos<s.size() && isDot(s[pos]) ) pos++;

        // Check the numbers after a dot '.'
        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

        // Check the 'e' / 'E'
        if ( haveNum && pos<s.size() && isE(s[pos]) ) {
            haveNum = false; pos++;
            if ( pos<s.size() && isSgn(s[pos]) ) pos++;
        }

        // Check the numbers after 'e' / 'E'
        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

        // Check all the remaining spaces
        while ( pos<s.size() && isSpace(s[pos]) ) pos++;

        // Everything is done, if the string not empty, return false.
        return ( pos==s.size() && haveNum );
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值