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

Tag: 剑指-Offer Posted on 2022-02-23 11:47:32 Edited on 2022-02-23 12:02:18 Views: 160

概述

https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/

解法

虽然我写过解释器吧,但是还是忽视了两点:

  1. 需要检查 dot 是否二次出现;
  2. 符号过后,下一个不为 . 时,其必须是数字;
class Solution {
public:
    int i = 0;
    bool isNumber(string s) {
        s.push_back('\0');
        while (s[i] == ' ') i ++;
        if (s[i] == '\0') return false;
        if (s[i] == '+' || s[i] == '-') i ++;
        if (s[i] == '\0') return false;
        bool dot = false;
        if (s[i] == '.') {
            dot = true;
            i ++;
            if (!isdigit(s[i])) return false;
            i ++;
        } else {
            if (!isdigit(s[i])) return false;
        }
        while (isdigit(s[i])) i ++;
        if (s[i] == '.') {
            if (dot) return false;
            i ++;
            while (isdigit(s[i])) i ++; 
        }
        if (s[i] == 'e' || s[i] == 'E') {
            i ++;
            if (s[i] == '+' || s[i] == '-') i ++;
            if (!isdigit(s[i])) return false;
            while (isdigit(s[i])) i ++;
        }
        while (i < s.size() - 1) {
            if (s[i] != ' ') return false;
            i ++;
        }
        return true;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/