Python O(n) solution with ifs


  • 0
    V
    import re
    
    class Solution(object):
        def isNumber(self, s):
            """
            :type s: str
            :rtype: bool
            """
            s = s.strip()
            pos = 0
            numberFound = False
            eNumberFound = True
            
            if not s:
                return False
            
            if s[pos] == '-' or s[pos] == '+':
                pos += 1
                
            while pos < len(s) and re.match("[0-9]+", s[pos]):
                numberFound = True
                pos += 1
            
            if pos < len(s) and s[pos] == '.':
                pos += 1
                while pos < len(s) and re.match("[0-9]+", s[pos]):
                    numberFound = True
                    pos += 1
        
            if pos < len(s) and s[pos] == 'e':
                if not numberFound:
                    return False
                eNumberFound = False
                pos += 1
            
            if not eNumberFound and pos < len(s) and (s[pos] == '-' or s[pos] == '+'):
                pos += 1
            
            while pos < len(s) and re.match("[0-9]+", s[pos]):
                eNumberFound = True
                pos += 1
            
            return pos == len(s) and numberFound and eNumberFound
                
    

Log in to reply
 

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