跳至主要内容

65. Valid Number

Hint

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

// Remove trailing spaces
// ex: s = "123 "

// Remove leading spaces
// ex: s = " 123"

// Indicates if a decimal point has been encountered
// Indicates if 'e' (exponent) has been encountered
// Indicates if any digit has been encountered

// Iterate through each character in the string
for ()
{
// Convert character to lowercase for uniform processing

// Check if the current character is a digit
if ()
{

}
// Check if the current character is a decimal point
else if ()
{
// Decimal point is not allowed if 'e' has been encountered or if there's already a decimal point
// ex: s = "99e2.5"
}
// Check if the current character is 'e' (exponent)
else if ()
{
// 'e' is not allowed if it has already been encountered or if there are no digits before it
// ex: s = "95a54e53", s = "e797537"
// Reset digit flag for the part after 'e'
}
// Check if the current character is a sign (+ or -)
else if ()
{
// A sign can only appear at the start or immediately after 'e'
}
else // Invalid character
}

// The string is valid if and only if at least one digit was found
}
};
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)