LeetCode Solutions

65. Valid Number

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  bool isNumber(string s) {
    trim(s);
    if (s.empty())
      return false;

    bool seenNum = false;
    bool seenDot = false;
    bool seenE = false;

    for (int i = 0; i < s.length(); ++i) {
      switch (s[i]) {
        case '.':
          if (seenDot || seenE)
            return false;
          seenDot = true;
          break;
        case 'e':
        case 'E':
          if (seenE || !seenNum)
            return false;
          seenE = true;
          seenNum = false;
          break;
        case '+':
        case '-':
          if (i > 0 && s[i - 1] != 'e')
            return false;
          seenNum = false;
          break;
        default:
          if (!isdigit(s[i]))
            return false;
          seenNum = true;
      }
    }

    return seenNum;
  }

 private:
  void trim(string& s) {
    s.erase(0, s.find_first_not_of(' '));
    s.erase(s.find_last_not_of(' ') + 1);
  }
};
			

class Solution {
  public boolean isNumber(String s) {
    s = s.trim();
    if (s.isEmpty())
      return false;

    boolean seenNum = false;
    boolean seenDot = false;
    boolean seenE = false;

    for (int i = 0; i < s.length(); ++i) {
      switch (s.charAt(i)) {
        case '.':
          if (seenDot || seenE)
            return false;
          seenDot = true;
          break;
        case 'e':
        case 'E':
          if (seenE || !seenNum)
            return false;
          seenE = true;
          seenNum = false;
          break;
        case '+':
        case '-':
          if (i > 0 && s.charAt(i - 1) != 'e')
            return false;
          seenNum = false;
          break;
        default:
          if (!Character.isDigit(s.charAt(i)))
            return false;
          seenNum = true;
      }
    }

    return seenNum;
  }
}
			

class Solution:
  def isNumber(self, s: str) -> bool:
    s = s.strip()
    if not s:
      return False

    seenNum = False
    seenDot = False
    seenE = False

    for i, c in enumerate(s):
      if c == '.':
        if seenDot or seenE:
          return False
        seenDot = True
      elif c == 'e' or c == 'E':
        if seenE or not seenNum:
          return False
        seenE = True
        seenNum = False
      elif c in '+-':
        if i > 0 and s[i - 1] != 'e':
          return False
        seenNum = False
      else:
        if not c.isdigit():
          return False
        seenNum = True

    return seenNum