[LeetCode] Ternary Expression Parser

439. Ternary Expression Parser

Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it.

You can always assume that the given expression is valid and only contains digits, ‘?’, ‘:’, ‘T’, and ‘F’ where ‘T’ is true and ‘F’ is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]).

The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, ‘T’ or ‘F’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
int find(string s) {
for(int i = 2, now = 1; i < s.length(); i++) {
if(s[i] == '?') now++;
else if(s[i] == ':') now--;
if(now == 0) return i;
}
return -1;
}
public:
string parseTernary(string expression) {
if(expression.find('?') == string::npos) return expression;
int cut = find(expression);
return expression[0] == 'T' ? parseTernary(expression.substr(2,cut - 2)) : parseTernary(expression.substr(cut+1));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/27/PS/LeetCode/ternary-expression-parser/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.