439 Ternary Expression Parser
1. Question
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 digits0-9
,?
,:
,T
andF
(T
andF
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
.
Example 1:
Example 2:
Example 3:
2. Implementation
思路:这是当年面Pocket Gem的电面题,当时的我完全懵逼无从入手...这道题既可以用递归,也可以用stack解。如果用stack的话,需要从后往前扫,这样的好处是当我们遇到'?'前面的character(T 或者 F),我们可以知道该保留‘?’后面的哪个expression
3. Time & Space Complexity
时间和空间复杂度都是O(n)
Last updated