剑指offer面试题20:表示数值的字符串

题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。

其数值可以定义为:a类型:A[.[B]][e|EC] 或b类型: .B[e|EC]

其中A、C是有符号整型数值,而B是无符号整型数值,就其判断是字符串是否满足其中两种类型中的一种。(题目给出s.length < 20,故不需要考虑大值的情况)充分考虑到各种情况。

第一步:先去除头部空格

第二步:判断是否符合A

第三步:判断是否符合A.B 或.B或A.E|eC

第四步:判断是否符合e|EC

第五步:判断尾部

class Solution {
public:
    int cheak_Int(const string& s, int n)      //核查字串中的数字部分
    {
        for(; n < s.size(); n++)
        {
            if(s[n] >= '0' && s[n] <= '9') continue;
            else break;
        }
        return n;
    }

    int cheak_Number(const string& s, int n)
    {
        int front = n;
        //判断A部分
        n = cheak_Int(s, n);
        if(s[n] == '.')
        {
            //判断是不是a类型特殊组成A.[e|EC/' ']
            if(n != front && (s[n + 1] < '0' || s[n + 1] > '9')) return n + 1;

            //不是特殊组成类型 去除字符'.',继续判断类型中的B部分
            n++;
            int front2 = n;
            n = cheak_Int(s, n);
            if(n == front2) return -1; //不符合A.B 或 .B
            else return n;

        }
        if(front == n) return -1; //不符合A 或 .B
        else return n;
        
    }

    bool isNumber(string s) {
        int n = 0;
        if(s.size() == 0) return false;
        for(; n < s.size(); n++)          //去掉头部空格字符
        {
            if(s[n] == ' ') continue;
            else break;
        }
        if(n == s.size()) return false;   //判断是不是全由空格组成
        if(s[n] == '-' || s[n] == '+') n++;   //去掉符号位
        n = cheak_Number(s, n);               //判断组成是否符合A[.B] 或 .B
        if(n == -1) return false;
        if(s[n] == 'e' || s[n] == 'E')        //判断字符串是否符合[e|EC]
        {
            n++;
            int temp = n;
            if(s[n] == '+' || s[n] == '-')
            {
                n++;
                temp = n;
                n = cheak_Int(s, n);
            }
            else 
            {
                temp = n;
                n = cheak_Int(s, n);
            }

            if(n == temp) return false;
        }

        if(n == s.size()) return true;
        if(s[n] == ' ')            //符合量类型后,判断尾部是否符合规矩(即均为空格)
        {
            for(; n < s.size(); n++)
            {
                if(s[n] == ' ') continue;
                else return false;
            }
            return true;
        }
        else return false;

        return true;
    }
};

运行结果:

猜你喜欢

转载自blog.csdn.net/m0_63001277/article/details/127004463