现在的位置: 首页 > 综合 > 正文

leetcode Valid Number

2019年04月01日 ⁄ 综合 ⁄ 共 1199字 ⁄ 字号 评论关闭

这道题目思路并不是很复杂,关键是很难一次考虑全面,从测试用例考虑一次需要考虑 :空串,仅含空格的串 ,带+、-符号的串,小数点,指数e以及后面必须有数 并且还要考虑符号的问题,最后要考虑串的最后是一系列空格的情况,我也是反复提交了几次才成功,代码如下

class Solution {
public:
     bool isNumber(const char *s) {
        const char *str=s;
        if(!str)return false;//空串
        int tmp=0;
        int point=0;
        while(*str!='\0'&& *str==' ')str++;
        if(*str=='\0')return false;//仅包含空格的串
        if(str[0]=='+'||str[0]=='-'){str++;if(('0'<=str[0]&&str[0]<='9')||str[0]=='.');else return false;}//处理符号
        else if(str[0]=='.'){point=1;str++;if('0'>str[0]||str[0]>'9') return false;}
        else if('0'>str[0]||str[0]>'9') return false;
        for(int i=0;i<strlen(str);i++)
        {     if(tmp==0)//处理指数e
                   if(i<strlen(str)-1){
                       if((str[i]=='e')&&(('0'<=str[i+1]&&str[i+1]<='9')||str[i+1]=='+'||str[i+1]=='-')){tmp=1;continue;}
               }
               if((str[i]=='.')&&(point==0)&&(tmp==0)){//处理小数点
                   if((i<strlen(str)-1)){
                   if(('0'<=str[i+1]&&str[i+1]<='9')||str[i+1]==' '||str[i+1]=='e'){point=1;continue;}
                   }else if(i>0&&('0'<=str[i-1]&&str[i-1]<='9'))return true;
               }
               if(str[i]==' '){//剩余部分为仅包含空格的串
                while(str[i]!='\0'&& str[i]==' ')i++;
                if(str[i]=='\0')return true;
                      else return false;;
               }
               if(str[i]=='+'||str[i]=='-'){//处理指数符号
                   if(str[i-1]=='e'){
                       if((i<strlen(str)-1)&&('0'<=str[i+1]&&str[i+1]<='9'))
                              continue;
                       else return false;
                   }
               }
               if('0'<=str[i]&&str[i]<='9')continue;
                else return false;
        }
        return true;
    }
};

抱歉!评论已关闭.