剑指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();
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36459662/article/details/113955408