Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to evaluate ternary expression in C++
Looking at this article, I can see it's about C++ but labeled as Python. I'll improve the structure, fix the HTML issues, and make it clearer while keeping the C++ content intact.
A ternary expression uses the format condition ? value1 : value2. Given a string representing nested ternary expressions with 'T' (True) and 'F' (False), we need to evaluate the final result.
Problem Constraints
- String length ? 10000
- Conditional expressions group right-to-left
- Conditions are always 'T' or 'F', never digits
- Final result is always 'T' or 'F'
For example, "T?T?F:T:T" evaluates to "F".
Algorithm
We use a stack-based approach, processing the expression from right to left:
- Traverse the string from right to left
- When we encounter a '?' on the stack top, we have a complete ternary expression
- Pop the condition, first value, colon, and second value
- Push the result based on the condition
- Continue until the entire expression is evaluated
Example
Let's trace through "T?T?F:T:T":
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
string parseTernary(string s) {
string ret = "";
int n = s.size();
stack<char> st;
for(int i = n - 1; i >= 0; i--){
char x = s[i];
if(!st.empty() && st.top() == '?'){
st.pop();
char first = st.top();
st.pop();
st.pop(); // Remove ':'
char second = st.top();
st.pop();
if(x == 'T'){
st.push(first);
} else {
st.push(second);
}
} else {
st.push(x);
}
}
while(!st.empty()){
ret += st.top();
st.pop();
}
reverse(ret.begin(), ret.end());
return ret;
}
};
int main(){
Solution ob;
cout << ob.parseTernary("T?T?F:T:T") << endl;
return 0;
}
How It Works
The expression "T?T?F:T:T" is processed as follows:
- Start from right: Push 'T', ':', 'T', '?', 'F', '?', 'T', '?', 'T'
- When we see 'T' and stack top is '?', we evaluate the inner ternary
- Inner expression:
T ? F : T? Result is 'F' - Continue with outer expression:
T ? F : T? Result is 'F'
Output
F
Time Complexity
Time: O(n) where n is the length of the input string
Space: O(n) for the stack
Conclusion
This stack-based approach efficiently evaluates nested ternary expressions by processing them right-to-left. The algorithm handles the right-associative nature of ternary operators correctly.
