[
math
parser
string
]
Leetcode 0065. Valid Number
Problem statement
https://leetcode.com/problems/valid-number/
Solution
Let us create functions:
is_integer(s), which check if number is integer: it can consist either of digits or have+or-in the beginning.decimal(s), which check if number is decimal: we split is using.and if we not2parts, we return false. Then we have three options: either first part is integer and second has only digits; or first part is empty or+or-and second part consists only digits; or first part is integer and second is empty.
Finally, we transform string to lower case and split, using e. If number of parts more than 2, return false. parts[0] must be integer or decimal, if it is not, return False. Finally, if we have second part, we check that it is integer.
Complexity
Time and space complexity is O(n), where n is length of string.
Code
class Solution:
def isNumber(self, s):
def is_integer(s):
return s.isdigit() or len(s) > 0 and s[0] in "+-" and s[1:].isdigit()
def is_decimal(s):
parts = s.split(".")
if len(parts) != 2: return False
if is_integer(parts[0]) and parts[1].isdigit(): return True
if parts[0] in ["","+","-"] and parts[1].isdigit(): return True
if is_integer(parts[0]) and not parts[1]: return True
return False
s = s.lower()
parts = s.split("e")
if len(parts) > 2: return False
if not is_integer(parts[0]) and not is_decimal(parts[0]): return False
return True if len(parts) == 1 else is_integer(parts[1])