Solution in Python


  • 0
    J

    A solution in Python. Could be better but this one passes:

    class Solution:
    def isNumber(self, s):
    s = s.strip()
    p_rep = False
    e_rep = False
    last = ""

        for i, n in enumerate(s):
            
            if n == '.':
                if last not in ['+', '-', ''] and (last < '0' or last > '9'):
                    return False
                if len(s) == 1 or p_rep or e_rep:
                    return False
                if last in ['+', '-'] and len(s) == i + 1:
                    return False
                p_rep = True
                
            elif n == 'e':
                if last == '.' and i < 2:
                    return False
                if last != '.' and last < '0' or last > '9' or len(s) == i + 1 or e_rep:
                    return False
                e_rep = True
                
            elif n == '+' or n == '-':
                if last not in ['e', ''] or len(s) == i + 1:
                    return False
                
            else:
                if n < '0' or n > '9':
                    return False
            
            last = n
            
        return bool(s)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.