439 Ternary Expression Parser
1. Question
Input:"T?2:3"
Output:"2"
Explanation:If true, then result is 2; otherwise result is 3.2. Implementation
3. Time & Space Complexity
Last updated
Input:"T?2:3"
Output:"2"
Explanation:If true, then result is 2; otherwise result is 3.Last updated
Input:"F?1:T?4:5"
Output:"4"
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))"
->"(F ? 1 : 4)" or -> "(T ? 4 : 5)"
->"4" -> "4"Input:"T?T?F:5:3"
Output:"F"
Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
"(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)"
-> "(T ? F : 3)" or -> "(T ? F : 5)"
-> "F" -> "F"class Solution {
public String parseTernary(String expression) {
if (expression == null || expression.length() == 0) {
return "";
}
Stack<Character> stack = new Stack<>();
for (int i = expression.length() - 1; i >= 0; i--) {
char c = expression.charAt(i);
if (!stack.isEmpty() && stack.peek() == '?') {
stack.pop();
char firstVal = stack.pop();
stack.pop();
char secondVal = stack.pop();
if (c == 'T') {
stack.push(firstVal);
}
else {
stack.push(secondVal);
}
}
else {
stack.push(c);
}
}
return String.valueOf(stack.pop());
}
}