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.


注意:"-1.", "46.e3" 一类是一个有效的数字, "6e6.5"一类不是有效的数字。

C++: http://en.cppreference.com/w/cpp/language/floating_literal

Python: https://docs.python.org/2/reference/lexical_analysis.html#floating-point-literals

Java: https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.2

这个方法比较好理解,但是速度比较慢,可以尝试下DFA(有限状态机)。

下面的方法是逐个判断:

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;

        while ( pos<s.size() && isSpace(s[pos]) ) pos++;

        if ( pos<s.size() && isSgn(s[pos]) ) pos++;

        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

        if ( pos<s.size() && isDot(s[pos]) )   pos++;//{haveNum=false;pos++;}
       
        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

     
        if ( haveNum && pos<s.size() && isE(s[pos]) ) {
            if ( pos<s.size() && isSgn(s[pos]) ) pos++;
        }

        while ( pos<s.size() && isNum(s[pos]) ) {haveNum = true; pos++;}

        while ( pos<s.size() && isSpace(s[pos]) ) pos++;
        return ( pos==s.size() && haveNum );
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值