forked from jsjtzyy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC439_TernaryExpressionParser.java
More file actions
30 lines (30 loc) · 1 KB
/
LC439_TernaryExpressionParser.java
File metadata and controls
30 lines (30 loc) · 1 KB
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
import java.util.*;
/*
use the stack and traverse from the end of string
when encoutnering '?', pop out the toppest two characters in stack, and choose the correct
to push back to stack based on character before '?'
*/
public class LC439_TernaryExpressionParser {
public String parseTernary(String expression) {
String res = new String();
Stack<Character> stack = new Stack<>();
if(expression == null || expression.length() < 5) return res;
char ch = ' ', first = ' ', second = ' ';
int len = expression.length();
for(int i = len - 1; i >= 0; --i){
ch = expression.charAt(i);
if(ch == 'T' || ch == 'F' || (ch >= '0' && ch <= '9')){
stack.push(ch);
}else if(ch == '?'){
first = stack.pop();
second = stack.pop();
if(expression.charAt(--i) == 'T'){
stack.push(first);
}else{
stack.push(second);
}
}
}
return String.valueOf(stack.pop());
}
}