劍指offer20題——leetcode主站65題

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

思路:

1. 首先去除字符串首尾字符

2. 根據小寫e劃分指數和底數

3. 分別對指數和底數判斷是否合法即可

class Solution {
public:
    bool judgeDigit(string s)
    {
        int len=s.size();
        bool flag_has_digit=false;
        bool point_flag=false;
        for(int i=0;i<len;i++)
        {
            if(s[i]=='+'||s[i]=='-')
            {
                if(i!=0)return false;   //+或-不出現在第一位則爲false
            }
            else if(s[i]=='.')
            {
                if(point_flag)return false; //多個點返回false
                point_flag=true;
            }
            else if(s[i]<'0'||s[i]>'9')
            {
                return false;   //出現除0-9,+,-,.,之外的字符返回false
            }
            else 
            {
                flag_has_digit=true;    //記錄是否出現了數字,最終判斷標誌
            }
        }
        if(flag_has_digit)
        return true;
        else return false;
    }
    
    bool judgeExponent(string s)    //與判斷底數相比的唯一差別:.的出現也是不合法的
    {
         int len=s.size();
         if(len==0)return false;
        bool flag_has_digit=false;
        bool point_flag=false;
        for(int i=0;i<len;i++)
        {
            if(s[i]=='+'||s[i]=='-')
            {
                if(i!=0)return false;
            }
            else if(s[i]<'0'||s[i]>'9')
                return false;
            else 
            {
                flag_has_digit=true;
            }
        }
      if(flag_has_digit)
        return true;
        else return false;
    }
    bool isNumber(string s) {
        int i=s.find_first_not_of(" "); //判斷是否有非空字符
        if(i==string::npos)
        {
            return false;
        }
        int j=s.find_last_not_of(" ");
        s=s.substr(i,j-i+1);
        int e=s.find("e");  
        if(e==string::npos)     //無e整體判斷
        {
            if(judgeDigit(s))return true;
            else return false;
        }
        else 
        {
            if(judgeDigit(s.substr(0,e))&&judgeExponent(s.substr(e+1))) //有e則分爲底數和指數判斷
                return true;
            else return false;
        }
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章