65. Valid Number
https://leetcode.com/problems/valid-number/
js
/**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
s = s.trim()
var num = false
var dot = false
var exp = false
for (let i = 0; i < s.length; i++) {
let c = s[i]
if (c >= '0' && c <= '9') {
num = true
} else if (c === '.') {
if (exp || dot) {
return false
}
dot = true
} else if (c === 'e') {
if (exp || !num) {
return false
}
exp = true
num = false
} else if (c === '+' || c === '-') {
if (i === 0) {
continue
}
if (s[i - 1] !== 'e') {
return false
}
} else {
return false
}
}
return num
}
py
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.strip()
num = dot = exp = False
for i, c in enumerate(s):
if c.isdigit():
num = True
elif c == '.':
if exp or dot:
return False
dot = True
elif c == 'e':
if exp or not num:
return False
exp, num = True, False
elif c == '+' or c == '-':
if i == 0:
continue
if s[i - 1] != 'e':
return False
else:
return False
return num