剑指 Offer 20. 表示数值的字符 (C++实现)

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

 来源:力扣(LeetCode) 链接:力扣

-> 符合 A[.[B]][e|EC] 或 .B[e|EC] 形式 即为表示数值的字符串,返回 true
其中A、C为整数、B为无符号整数

// ->符合 A[.[B]][e|EC] 或 .B[e|EC] 形式
// 其中A、C为整数、B为无符号整数
​
// 判断是否为 无符号整数
bool scanUnsignedInt(string& s, int& index)
{
    int preIndex = index;
    while (index < s.size() && s[index] >= '0' && s[index] <= '9')
    {
        ++index;
    }
​
    return index > preIndex;
}
​
// 判断是否为 整数
bool scanInt(string& s, int& index)
{
    if (index < s.size() && (s[index] == '+' || s[index] == '-'))
    {
        ++index;
    }
    return scanUnsignedInt(s, index);
}
​
​
bool isNumber(string s) {
​
    // base case
    if (s.empty())
    {
        return false;
    }
​
    int index = 0;
​
    while (index < s.size() && s[index] == ' ')     // 除去前置空格
    {
        ++index;
    }
​
    bool res = scanInt(s, index);                   // 扫描A部分
​
    if (index < s.size() && s[index] == '.')
    {
        ++index;
        res = scanUnsignedInt(s, index) || res;     // 扫描B部分
    }
​
    if (index < s.size() && (s[index] == 'e' || s[index] == 'E'))
    {
        ++index;
        res = res && scanInt(s, index);             // 扫描C部分
    }
​
    while (index < s.size() && s[index] == ' ')     // 除去后置空格
    {
        ++index;
    }
​
    return res && index == s.size();
}
res = scanUnsignedInt(s, index) || res;     // 扫描B部分

顺序很重要,不可写成 res || scanUnsignedInt(s, index)

否则 scanUnsignedInt(s, index) 很可能不被执行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值