Leetcode # 65. Valid Number
https://leetcode.com/problems/valid-number
Solution
Time Complexity: O(len(s))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution: def isNumber(self, s: str) -> bool: stack = "" for c in s: match c: case "E" | "e": # "e" stack += "e" case "+" | "-": # "s" stack += "s" case ".": stack += "." case _: # "d" o = ord(c) if o < 48 or o > 57: return False if stack == "" or stack[-1] != "d": stack += "d" pattern = { "D":["d.d", "d.", ".d"], "N":["sD", "D"], "I":["sd", "d"] } for key in ["D", "N", "I"]: for p in pattern[key]: stack = stack.replace(p, key) match stack: case "I" | "N" | "NeI" | "IeI": return True return False
Last Updated on 2023/08/16 by A1go