Leetcode 439 Solution
This article provides solution to leetcode question 439 (ternary-expression-parser)
Access this page by simply typing in "lcs 439" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/ternary-expression-parser
Solution
class Solution:
def parseTernary(self, expression: str) -> str:
i = 0
def parse():
nonlocal i
ch = expression[i]
if ch.isnumeric():
v = 0
while i < len(expression) and expression[i].isnumeric():
v = 10 * v + int(expression[i])
i += 1
return str(v)
elif ch in ["T", "F"]:
if i == len(expression) - 1 or expression[i + 1] != '?':
i += 1
return ch
else:
cond = ch == "T"
i += 2
v1 = parse()
i += 1
v2 = parse()
if cond:
return v1
else:
return v2
return str(parse())