Simple Python submission from contest. O(n) time


  • 1

    My contest submission with minimal cleanup:

    def parseTernary(self, s):
        stack = list(s)[::-1]
        def helper():
            if len(stack) == 1: return stack[0]
            n = stack.pop()
            op = stack.pop()
            if op == ':': return n
            a = helper()
            b = helper()
            return a if n == 'T' else b
        return helper()
    

  • 0

    Nice one. Just two variations:

    def parseTernary(self, s):
        stack = list(s)[::-1]
        def helper():
            n = stack.pop()
            if not stack or stack.pop() == ':':
                return n
            return (helper(), helper())[n == 'F'] 
        return helper()
    
    def parseTernary(self, s):
        chars = iter(s + ':')
        def helper():
            n = next(chars)
            if next(chars) == ':':
                return n
            return (helper(), helper())[n == 'F'] 
        return helper()
    

    Could use return ... if ... else ... there, but somehow I like it better in three lines here.


Log in to reply
 

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