-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path439 Ternary Expression Parser.py
68 lines (55 loc) · 1.63 KB
/
439 Ternary Expression Parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/python3
"""
Premium question
Author: Rajeev Ranjan
"""
class Solution:
def parseTernary(self, expression: str) -> str:
"""
stk from right to left parsing, including the operand and operator
"""
stk = []
for c in reversed(expression):
if stk and stk[-1] == "?":
stk.pop() # ?
first = stk.pop()
stk.pop() # :
second = stk.pop()
if c == "T":
stk.append(first)
else:
stk.append(second)
else:
stk.append(c)
return stk[0]
def parseTernary_complex(self, expression: str) -> str:
"""
tokenize + recursive (dfs)?
stk from right to left, only include the operand
can handle multiple digit (not required)
"""
n = len(expression)
stk = []
i = n - 1
while i >= 0:
j = i
while j >= 0 and expression[j] not in (":", "?"):
j -= 1
if j < i:
stk.append(expression[j+1:i+1])
if expression[j] == ":":
i = j - 1
else: # "?"
i = j - 1
if expression[i] == "T":
a = stk.pop()
stk.pop()
stk.append(a)
i -= 1
else:
stk.pop()
i -= 1
return stk[0]
if __name__ == "__main__":
assert Solution().parseTernary("F?1:T?4:5") == "4"
assert Solution().parseTernary("T?T?F:5:3") == "F"