假设我们有一个保存三元表达式的表达式,我们必须评估该表达式的结果。它支持T和F等True和False以及“?”值 和“:”字符。有一些属性:
给定字符串的长度必须小于或等于10000。
条件表达式从右到左分组。
条件将始终为T或F。因此,条件将永远不是数字。
表达式的结果将始终为T或F。
因此,例如,如果输入像“ T??F:T:T”,因此输出将为F。
让我们看下面的实现以更好地理解:
#include
using namespace std;
class Solution {
public:
string parseTernary(string s) {
string ret = "";
int n = s.size();
stack 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("T?T?F:T:T"));
}" T?T?F:T:T"
输出结果
F