65. Valid Number - cocoder39/coco39_LC GitHub Wiki
2nd revision
- sign: has to be leading eg 6+1 is invalid
- int: 0 or 1 leading sign, followed by digits, no decimal
- once a sign is found, no more sign
- if it is int (eg following exp), there is no decimal
- no digit is invalid eg .
- decimal: 0 or 1 leading sign
- definition
- decimal + digit eg .4
- digit + decimal eg 3.
- digit + decimal + digit 3.4
- violation
- once a sign is found, no more sign
- once a decimal is found, no more decimal
- no digit is invalid
- definition
- exp: e/E followed by int
- there should be digit before and after e/E, eg e is invalid
- once e/E is found, no more e eg 3e4e is invalid
- any char that is not digit, sign, e/E, decimal, then it is invalid
- valid number: int or decimal followed by 0 or 1 exp
class Solution:
def isNumber(self, s: str) -> bool:
canHaveSign = True
canHaveDecimalPoint = True
canHaveExp = True
hasDigit = False
for ch in s:
if ch in '+-':
if not canHaveSign:
return False
canHaveSign = False
elif ch in 'Ee':
if not canHaveExp or not hasDigit:
return False
canHaveSign = True
canHaveDecimalPoint = False
canHaveExp = False
hasDigit = False
elif ch == '.':
if not canHaveDecimalPoint:
return False
canHaveSign = False
canHaveDecimalPoint = False
elif ch.isdigit():
canHaveSign = False
hasDigit = True
else:
return False
return hasDigit
class Solution:
def isNumber(self, s: str) -> bool:
seen_digit = seen_exp = seen_dot = False
for i, ch in enumerate(s):
if ch.isdigit():
seen_digit = True
elif ch in '+-':
if i > 0 and s[i-1] not in 'eE':
return False
elif ch in 'eE':
if seen_exp or not seen_digit:
return False
seen_exp = True
seen_digit = False
elif ch == '.':
if seen_dot or seen_exp:
return False
seen_dot = True
else:
return False
return seen_digit