Leetcode_valid-number(updated c++ and python version)

本文介绍了一种判断给定字符串是否为有效数字的方法,并提供了详细的解析逻辑及C++与Python实现示例。

地址:http://oj.leetcode.com/problems/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. 首先去除首尾空格

2. 剔除开始的'+' 或者 '-' (If exists)

3. 上述两个操作之后,可能包含的非数字字符:'e' '.' '+' '-' 并且最多只能出现一次

其中’ . ‘ 不能出现在' e '之后,

’+‘ 或 ’-‘ 应该紧接着'e' 并且'+' 或者'-'不能是除空格之外的最后一位

’e‘ 不能紧接着'.'出现,中间要有数字,比如3.7e-10

参考代码:

class Solution {
public:
    bool isNumber(const char *s) {
        if(!s)
            return false;
        while(s && *s == ' ')
            ++s;
        int len = strlen(s);
        if(!len)
            return false;
        const char *end = s+len-1;
        while(end>s && *end--==' ')
            --len;
        if(*s=='-' || *s=='+')
        {
            --len;
            ++s;
        }
        int pos_e = -1, pos_dot = -1, pos_plus=-1, pos_minus=-1;
        bool has_num = false;
        for(int i = 0; i<len; ++i)
        {
            if(*(s+i)>='0' && *(s+i)<='9')
                has_num = true;
            else if(*(s+i)=='.')
            {
                if(pos_dot>=0)
                    return false;
                pos_dot = i;
                if(pos_e>=0)
                    return false;
            }
            else if(*(s+i)=='e')
            {
                if(pos_e>=0 || i==0 || i==len-1)
                    return false;
                pos_e = i;
                if(pos_dot>=0 && pos_dot+1==pos_e && (i==len-1 || pos_dot==0))
                    return false;
            }
            else if(*(s+i)=='+')
            {
                if(pos_plus>=0)
                    return false;
                pos_plus = i;
                if(pos_e==-1 || pos_plus>pos_e+1 || i==len-1)
                    return false;
            }
            else if(*(s+i)=='-')
            {
                if(pos_minus>=0)
                    return false;
                pos_minus = i;
                if(pos_e==-1 || pos_minus>pos_e+1 || i==len-1)
                    return false;
            }
            else
                return false;
        }
        return has_num;
    }
};

思路:用python投机取巧可以么

参考代码:

class Solution:
    # @param s, a string
    # @return a boolean
    def isNumber(self, s):
        s = s.strip()
        if not s: return False
        try:
            float(s)
        except Exception, e:
            return False
        else:
            return True
            


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值