LeetCode刷题实战439:三元表达式解析器
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 or F. That is, the condition will never be a digit.
The result of the expression will always evaluate to either a digit 0-9, T or F.
示例
示例 1:
输入:“T?2:3”
输出:“2”
解释:如果条件为真,结果为 2;否则,结果为 3。
示例 2:
输入:“F?1:T?4:5”
输出:“4”
解释:条件表达式自右向左结合。使用括号的话,相当于:
"(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))"
-> "(F ? 1 : 4)" 或者 -> "(T ? 4 : 5)"
-> "4" -> "4"
示例 3:
输入:“T?T?F:5:3”
输出:“F”
解释:条件表达式自右向左结合。使用括号的话,相当于:
"(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)"
-> "(T ? F : 3)" 或者 -> "(T ? F : 5)"
-> "F" -> "F"
解题
class Solution {
public:
string parseTernary(string expression) {
if(expression.size()==1){//表达式的长度为1时,直接返回结果
return expression;
}
//辅助变量,找出当前三元表达式的对应的 :的位置
int pos=2;
int counts=0;
while(posif(expression[pos]=='?'){//统计随后出现的?,来匹配对应的随后的:
++counts;
}
else if(expression[pos]==':'){
if(counts==0){//说明是当前的三元表达式的:,可以跳出循环
break;
}
--counts;
}
++pos;
}
//根据起始的字符是T或F,决定递归判断下一个表达式
if(expression[0]=='T'){
return parseTernary(expression.substr(2,pos-2));
}
return parseTernary(expression.substr(pos+1));
}
};