I just keep trying and correcting: C++ solution


  • 0
    T
    class Solution {
    public:
        bool isNumber(string s) {
            int n = s.length();
            int left = 0;
            int right = s.length()-1;
            while(left<n && s[left] == ' ')
            {
                left++;
            }
            while(right>=0 && s[right] == ' ')
            {
                right--;
            }
            if(left>right)
                return false;
                
            if(left<n && (s[left] == '+' || s[left] == '-'))
            {
                left++;
            }
            if(left>right)
                return false;
                
            bool hasDot = false;
            bool hasE   = false;
            bool hasN   = false;
            for(int i=left; i<=right; i++)
            {
                if(s[i]=='.')
                {
                    if(hasDot)
                        return false;
                    hasDot = true;
                    if(left==right)
                        return false;
                    if(hasE)
                        return false;
                    if(i-1>=0 && s[i-1] == 'e')
                        return false;
                }
                else if(s[i]=='e')
                {
                    if(hasE)
                        return false;
                    hasE = true;
                    if(!hasN)
                        return false;
                    if(i+1<n && s[i+1]=='.')
                        return false;
                    if(i==left || i==right)
                        return false;
                }
                else if(s[i]=='+' || s[i]=='-')
                {
                    if(i-1>=0 && s[i-1]!='e')
                        return false;
                    if(i==right)
                        return false;
                }
                else if(s[i]>='0' && s[i]<='9')
                    hasN = true;
                else
                    return false;
            }
            
            return true;
            
        }
    };

Log in to reply
 

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