算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 三元表达式解析器,我们先来看题面:​​

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.

给定一个以字符串表示的任意嵌套的三元表达式,计算表达式的值。你可以假定给定的表达式始终都是有效的并且只包含数字 0-9, ?, :, T 和 F (T 和 F 分别表示真和假)。

注意:给定的字符串长度 ≤ 10000。所包含的数字都只有一位数。条件表达式从右至左结合(和大多数程序设计语言类似)。条件是 T 和 F其一,即条件永远不会是数字。表达式的结果是数字 0-9, T 或者 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"


解题

主要思路:(1)每次找出当前需要判断的三元表达式的三部分,后面两部分使用和?匹配的:进行分割,注意匹配的关系;(2)根据第一个表达式是T或F决定使用后面两部分中的哪一个作为下一次需要判断的表达式,来进行递归的调用,知道表达式的长度为1时,直接返回结果;

class Solution {
public:
string parseTernary(string expression) {
if(expression.size()==1){//表达式的长度为1时,直接返回结果
return expression;
}
//辅助变量,找出当前三元表达式的对应的 :的位置
int pos=2;
int counts=0;
while(pos<expression.size()){
if(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));
}
};



​LeetCode刷题实战439:三元表达式解析器_git