8ms c++ solution.


  • 0
    class Solution {
    public:
    bool digit(char a)  {return a<='9' && a>='0';    }
    string rmspace(string &s){  // remove the spaces in the beginning and at the end of the string
        int i=0,j=s.size()-1;
        while (i<=j && s[i]==' ') i++;
        while (j>=i && s[j]==' ') j--;
        int len = j-i+1;
        return s.substr(i,len);
    }
    bool isNumber(string s) {
        s = rmspace(s);
        if (s.empty()) return 0;
        int k=s.size();
        int index = 0;
        bool flag=false;
        if (s[0]=='-' || s[0]=='+') index++;
        if (digit(s[index])) flag=true;   // the integer part is not empty, i.e., not the form of .44
        while (index<k && digit(s[index]))  index++;
        if (index==k) return true;
        if (s[index]=='.')
        {
            index++;
            while (index<k && digit(s[index]))  index++;
            if (!flag && !digit(s[index-1])) return false;  // either the integar part or the fractional part or both should exist.
            if (index==k) return true;
            flag = true;
        }
        if (flag && s[index]=='e')
        {
            index++;
            if (s[index]=='-' || s[index]=='+') index++;
            if (index>=k) return false;
            while (index<k && digit(s[index]))  index++;
            if (!digit(s[index-1])) return false;
            else if (index==k) return true;
            else  return false;
        }
        else
            return false;
       
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.