O(n) C++ solution


  • 0
    N

    Time O(N)
    Use isNumeric flag

    class Solution {
    public:
        bool isNumber(string s) {
            int i = 0, len = s.length(), points = 0, digits = 0;
            bool isNumeric = false;
            while (i < len && isspace(s[i])) i++;
            if (i < len && (s[i] == '+' || s[i] == '-')) i++;
            
            while (i < len && (isdigit(s[i]) || s[i] == '.')) {
                if (isdigit(s[i])) digits++;
                if (s[i] == '.') points++;
                isNumeric = true;
                i++;
            }
            if (digits == 0 || points > 1) isNumeric = false;
            
            if (isNumeric && i < len && s[i] == 'e') {
                i++;
                isNumeric = false;
                if (i < len && (s[i] == '+') || s[i] == '-') i++;
                while (i < len && isdigit(s[i])) {
                    i++;
                    isNumeric = true;
                }
            }
            
            while (i < len && isspace(s[i])) i++;
            return isNumeric && i == len;
        }
    };
    

Log in to reply
 

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