439 Ternary Expression Parser

1. Question

Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits0-9,?,:,TandF(TandFrepresent True and False respectively).
Note:
  1. 1.
    The length of the given string is ≤ 10000.
  2. 2.
    Each number will contain only one digit.
  3. 3.
    The conditional expressions group right-to-left (as usual in most languages).
  4. 4.
    The condition will always be eitherTorF. That is, the condition will never be a digit.
  5. 5.
    The result of the expression will always evaluate to either a digit0-9,TorF.
Example 1:
1
Input:"T?2:3"
2
3
Output:"2"
4
5
Explanation:If true, then result is 2; otherwise result is 3.
Copied!
Example 2:
1
Input:"F?1:T?4:5"
2
3
Output:"4"
4
5
6
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
7
8
"(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))"
9
->"(F ? 1 : 4)" or -> "(T ? 4 : 5)"
10
->"4" -> "4"
Copied!
Example 3:
1
Input:"T?T?F:5:3"
2
3
4
Output:"F"
5
6
7
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
8
9
"(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)"
10
-> "(T ? F : 3)" or -> "(T ? F : 5)"
11
-> "F" -> "F"
Copied!

2. Implementation

(1) Stack
思路:这是当年面Pocket Gem的电面题,当时的我完全懵逼无从入手...这道题既可以用递归,也可以用stack解。如果用stack的话,需要从后往前扫,这样的好处是当我们遇到'?'前面的character(T 或者 F),我们可以知道该保留‘?’后面的哪个expression
1
class Solution {
2
public String parseTernary(String expression) {
3
if (expression == null || expression.length() == 0) {
4
return "";
5
}
6
7
Stack<Character> stack = new Stack<>();
8
9
for (int i = expression.length() - 1; i >= 0; i--) {
10
char c = expression.charAt(i);
11
12
if (!stack.isEmpty() && stack.peek() == '?') {
13
stack.pop();
14
15
char firstVal = stack.pop();
16
stack.pop();
17
char secondVal = stack.pop();
18
19
if (c == 'T') {
20
stack.push(firstVal);
21
}
22
else {
23
stack.push(secondVal);
24
}
25
}
26
else {
27
stack.push(c);
28
}
29
}
30
return String.valueOf(stack.pop());
31
}
32
}
Copied!
(2) DFS
1
class Solution {
2
public String parseTernary(String expression) {
3
int len = expression.length();
4
5
if (len == 1) {
6
return expression;
7
}
8
9
int count = 0;
10
for (int i = 0; i < len; i++) {
11
if (expression.charAt(i) == '?') {
12
++count;
13
}
14
else if (expression.charAt(i) == ':') {
15
--count;
16
17
// When the number of '?' matches with ':', we get a valid expression
18
if (count == 0) {
19
if (expression.charAt(0) == 'T') {
20
// Get the expression before ':', skip 'T' and '?' at the beginning
21
return parseTernary(expression.substring(2, i));
22
}
23
else {
24
// Get the expression after ':'
25
return parseTernary(expression.substring(i + 1));
26
}
27
}
28
}
29
}
30
return "";
31
}
32
}
Copied!

3. Time & Space Complexity

Stack: 时间复杂度O(n), 空间复杂度O(n)
DFS: 时间复杂度O(n), 空间复杂度O(n)