Python Divide and Conquer solution


  • 0

    Runtime: 42ms, 100%

    def parse(s, i, j):
        if j - i == 1:
            return s[i]
        check = s[i] == 'T'
        d = 0
        i += 2
        for x in xrange(i, j):
            n = s[x]
            if n == '?':
                d += 1
            elif n == ':':
                if d:
                    d -= 1
                else:
                    if check:
                        return parse(s, i, x)
                    return parse(s, x + 1, j)
    
    class Solution(object):
        def parseTernary(self, expression):
            """
            :type expression: str
            :rtype: str
            """
            return parse(expression, 0, len(expression))
    

Log in to reply
 

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