剑指offer Leetcode 20.表示数值的字符串

image-20201202215735214

思想:

字符串的模式

image-20201202220843398

代码:

class Solution {
private:
    //扫描整数,如果有符号则跳过符号,去扫描无符号整数
    //要改变index,记得传引用
    bool scanInteger(const string s, int& index){
        if(s[index] == '+' || s[index] == '-')
            ++index;
        return scanUnsignedInteger(s, index);
    }
    //扫描无符号整数,index增加了则返回真
    bool scanUnsignedInteger(const string s, int& index){
        int before = index;
        while(index != s.size() && s[index] >= '0' && s[index] <= '9')
            index++;
        return index > before;
    }
public:
    bool isNumber(string s) {
        if(s.size() == 0)
            return false;
        int index = 0;

        //跳过字符串前面的空格
        while(s[index] == ' ')
            ++index;
        //扫描整数,扫描完index上应该是非整数或到底
        bool numeric = scanInteger(s, index);

        //如果遇到.
        if(s[index] == '.'){
            ++index;
            //小数点前后至少有一个有数,用||,小数点后面只能是无符号
            numeric = scanUnsignedInteger(s, index) || numeric;
        }
        //遇到e或E,后面可以是带符号整数
        if(s[index] == 'e' || s[index] == 'E'){
            ++index;
            //要用&&,出现了e或E后面一定要有数
            numeric = numeric && scanInteger(s, index);
        }
        //去除后面的空格
        while(s[index] == ' ')
            ++index;
        return numeric && index == s.size();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值