当前位置:网站首页>20. string representing numeric value

20. string representing numeric value

2022-06-12 05:19:00 Be your goat

The finger of the sword Offer 20. String representing the value

Ideas : Simulate traversal

  • Remove leading and trailing spaces

  • Define flag num,dot,exp

  • Traversal string

    • If a character other than a valid character appears , Go straight back to false
    • If the current character is a number , Set up num by true
    • If the current character is .
      • If it appears in E and e or . after , namely dot or exp by true, return false
      • Set up dot by true
    • If the current character is E or e
      • If no numbers have appeared before or have appeared E or e, namely num by false or exp by true, return false
      • Set up exp by true,num by false, because e Must have a number after
    • If the current character is + and -, Judge whether it is the first character or e First character after
  • Traverse complete ,num It is the result.

class Solution {
public:
    bool isNumber(string s) {
        int startIdx=0,endIdx=s.size()-1;
        while(startIdx<=endIdx&&s[startIdx]==' ')startIdx++;
        while(startIdx<=endIdx&&s[endIdx]==' ')--endIdx;
        if(startIdx>endIdx) return false;
        bool dot=false,num=false,exp=false;
        for(int i=startIdx;i<=endIdx;++i){
            if(s[i]>='0'&&s[i]<='9'){
                num=true;
            }
            else if(s[i]=='.'){
                if(dot||exp)
                    return false;
                dot=true;
            }
            else if(s[i]=='e'||s[i]=='E'){
                if(exp||!num)
                    return false;
                exp=true;
                num=false;
            }
            else if(s[i]=='+'||s[i]=='-'){
                if(i!=startIdx&&s[i-1]!='E'&&s[i-1]!='e')
                    return false;
            }
            else return false;
        }
        return num;
    }
};

Time complexity O(n)

Spatial complexity O(1)

原网站

版权声明
本文为[Be your goat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010618459119.html