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

题目链接:剑指 Offer 20. 表示数值的字符串

方法:模拟

解题思路

根据题意模拟,详情见代码注释。

代码

class Solution {
public:
    bool isDecimal(string s){
        int first_symbol = s.find_first_of('.'); // 第一个'.'的位置
        int last_symbol = s.find_last_of('.'); // 最后一个'.'的位置
        if (first_symbol != last_symbol || first_symbol == string::npos) return false; // 当有多个'.' 或者 没有时,false
        bool flag = true;
        if (s[0] == '-' || s[0] == '+') { // eat '-' / '+',同时更新first_sybol
            s = s.substr(1);
            first_symbol -- ;
        }
        if (s[0] == '.') { // 小数情况-3
            if (s.length() == 1) flag = false;
            else {
                for (int i = 1; i < s.length(); i ++ ) {
                    if (s[i] >= '0' && s[i] <= '9') continue;
                    else {
                        flag = false;
                        break;
                    }
                }
            }
        } else { // 小数情况-1、2
            for (int i = 0; i < s.length(); i ++ ) {
                if (i == first_symbol) continue;
                if (s[i] >= '0' && s[i] <= '9') continue;
                else {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    bool isInteger(string s){
        if (s.length() == 1 && (s[0] == '-' || s[0] == '+')) return false;
        if (s[0] == '-' || s[0] == '+') s = s.substr(1); // eat '-' / '+'
        for (int i = 0; i < s.length(); i ++ ) {
            if (s[i] >= '0' && s[i] <= '9') continue;
            return false;
        }
        if (s.length() == 0) return false;
        return true;
    }

    bool isNumber(string s) {
        int l = 0, r = s.length() - 1;
        while (s[l] == ' ' && l < r) l ++ ;
        while (s[r] == ' ' && r > l) r -- ;
        s = s.substr(l, r - l + 1);
        if (s.length() == 1 && s == " ") return false;
        
        int first_E = s.find_first_of("eE"); // 查找s中第一个'e' / 'E'的位置
        int last_E = s.find_last_of("eE"); // 查找s中最后一个'e' / 'E'的位置
        if (first_E != last_E) return false;
        
        if (first_E == string::npos) return isInteger(s) || isDecimal(s);
        else { // 按照e/E分为两边
            string str1 = s.substr(0, first_E), str2 = s.substr(first_E + 1);
            return (isInteger(str1) || isDecimal(str1)) && isInteger(str2);
        }
    }
};

复杂度分析

时间复杂度:\(O(n)\)
空间复杂度:\(O(1)\)

posted @ 2023-04-08 22:45  lixycc  阅读(19)  评论(0)    收藏  举报