[leetcode] 65. Valid Number 解题报告

62 篇文章 0 订阅
46 篇文章 0 订阅

题目链接:https://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.


思路:这种字符串处理的题目烦的很,corner case 太多而且题目说的也不清楚,需要注意的是下面几种case (.54343)这种数据是合法的,(.)这个数据是不合法的,323e这种数据是不合法的,e后面需要跟数字,并且还可能有符号.开头结尾可能有空格.

我们可以设置两个计数器,一个用来测试字符串是否能够按照规定的字符走完,另一个用于标记是否出现了非法的case,比如e后面没有跟数据,或者e不能出现在首位,因为比如:1.2e+12这种是科学计数法,表示1.2*(10^12),所以e之前必须有数据.

代码如下:

class Solution {
public:
    bool isNumber(string s) {
        int i =0, k =0, len = s.size();
        while(s[i]==' ') i++;
        if(s[i]=='+' || s[i] == '-') i++;
        while(isdigit(s[i])) i++, k++;
        if(s[i] == '.') i++;
        while(isdigit(s[i])) i++, k++;
        if(k ==0) return false;
        if(s[i] == 'e')
        {
            i++, k = 0;
            if(s[i]=='+' || s[i] == '-') i++;
            while(isdigit(s[i])) i++, k++;
            if(k == 0) return false;
        }
        while(s[i] == ' ') i++;
        return i == len;
    }
};

参考:https://leetcode.com/discuss/88730/rainbow-concise-clearer-implementaiton-detailed-comments


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值