题意:
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits 0-9
, ?
, :
, T
and F
(T
and F
represent True and False respectively).
Note:
- The length of the given string is ≤ 10000.
- Each number will contain only one digit.
- The conditional expressions group right-to-left (as usual in most languages).
- The condition will always be either
T
orF
. That is, the condition will never be a digit. - The result of the expression will always evaluate to either a digit
0-9
,T
orF
.
从右向左遍历字符串,若当前字符为数字、F或T时入栈;若为‘?’, 根据'?'前面的F或T,留下正确的字符;若为‘:’,直接忽略。
class Solution {
public:
string parseTernary(string expression) {
stack<char> oprd;
for (int i = expression.size() - 1; i >= 0; i--){
if (isalnum(expression[i]))
oprd.push(expression[i]);
else if (expression[i] == '\?'){
--i;
if (expression[i] == 'F')
oprd.pop();
else{
char ch = oprd.top();
oprd.pop();
oprd.top() = ch;
}
}
}
return string("") + oprd.top();
}
};