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,?,:,TandF(TandFrepresent True and False respectively).

Note:

  1. The length of the given string is ≤ 10000.

  2. Each number will contain only one digit.

  3. The conditional expressions group right-to-left (as usual in most languages).

  4. The condition will always be eitherTorF. That is, the condition will never be a digit.

  5. The result of the expression will always evaluate to either a digit0-9,TorF.

Example 1:

Input:"T?2:3"

Output:"2"

Explanation:If true, then result is 2; otherwise result is 3.

Example 2:

Example 3:

2. Implementation

(1) Stack

思路:这是当年面Pocket Gem的电面题,当时的我完全懵逼无从入手...这道题既可以用递归,也可以用stack解。如果用stack的话,需要从后往前扫,这样的好处是当我们遇到'?'前面的character(T 或者 F),我们可以知道该保留‘?’后面的哪个expression

(2) DFS

3. Time & Space Complexity

Stack: 时间复杂度O(n), 空间复杂度O(n)

DFS: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?