Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ternary Expression Parser in C++
Suppose we have a string representing arbitrarily nested ternary expressions, we have to calculate the result of the expression. we can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F these few characters. (Here T and F represent True and False respectively). There are some properties −
The length of the given string must be less than or equal to 10000.
Each number will contain only one digit.
The conditional expressions group right-to-left.
The condition will always be either T or F. So the condition will never be a digit.
The result of the expression will always evaluate to either a digit 0-9, T or F.
So for example, if the input is like “F?1:T?4:5”, so the output will be 4, as it will parse the rightmost expression “T?4:5”, it will return 4, then the main expression will be “F?1:4”, so the returned value is 4.
To solve this, we will follow these steps −
ret := an empty string, n := size of s, create a stack st
-
for I in range n – 1 down to 0
x := s[i]
-
if st is not empty and top of stack is ‘?’, then
delete from st
first := top of st, then delete two elements from the stack
second := top of the stack, and delete from st
if x is T, then insert first into st, otherwise insert second into st
otherwise, insert x into st
-
while st is not empty, then
ret := ret + top of st and delete from st
reverse ret and return ret
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
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();
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;
}
};
main(){
Solution ob;
cout << (ob.parseTernary("F?1:T?4:5"));
}
Input
"F?1:T?4:5"
Output
4