65. Valid Number

class Solution {
public:
    bool isNumber(string s)
    {
        // Check if the string is empty; if so, it's not a valid number
        if (s.empty()) return false;

        // Remove trailing spaces
        while (s.back() == ' ') s.pop_back();

        // Remove leading spaces
        while (s.front() == ' ') s.erase(s.begin());

        bool dot = false;  // Indicates if a decimal point has been encountered
        bool e = false;    // Indicates if 'e' (exponent) has been encountered
        bool digit = false; // Indicates if any digit has been encountered

        // Iterate through each character in the string
        for (int i = 0; i < s.size(); ++i)
        {
            s[i] = tolower(s[i]); // Convert character to lowercase for uniform processing

            // Check if the current character is a digit
            if (isdigit(s[i]))
            {
                digit = true;
            }
            // Check if the current character is a decimal point
            else if (s[i] == '.')
            {
                // Decimal point is not allowed if 'e' has been encountered or if there's already a decimal point
                if (e || dot) return false;
                dot = true;
            }
            // Check if the current character is 'e' (exponent)
            else if (s[i] == 'e')
            {
                // 'e' is not allowed if it has already been encountered or if there are no digits before it
                if (e || !digit) return false;
                e = true;
                digit = false; // Reset digit flag for the part after 'e'
            }
            // Check if the current character is a sign (+ or -)
            else if (s[i] == '-' || s[i] == '+')
            {
                // A sign can only appear at the start or immediately after 'e'
                if (i != 0 && s[i - 1] != 'e') return false;
            }
            else return false; // Invalid character
        }

        // The string is valid if and only if at least one digit was found
        return digit;
    }
};
  • T: O(N)O(N)
  • S: O(1)O(1)