Very easy to understand python solution, beats 98.8%


  • 0
    Z

    The idea is to find the ":" belongs to the first "?", then if The first character is T, we just need to look at the data before ":", otherwise we need to look at the data after ":".

    class Solution(object):
        def parseTernary(self, exp):
            if len(exp) == 1: return exp[0]
            balance = -1
            for i in range(3, len(exp) - 1):
                if exp[i] =='?':
                    balance -= 1
                if exp[i] == ':':
                    balance += 1
                if balance == 0:
                    break
            if exp[0] == 'T':
                return self.parseTernary(exp[2: i])
            return self.parseTernary(exp[i + 1:])
    

Log in to reply
 

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