Ternary Expression Parser

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 either

    T

    or

    F

    . That is, the condition will never be a digit.

  5. The result of the expression will always evaluate to either a digit

    0-9

    ,

    T

    or

    F

    .

Example 1:

Example 2:

Example 3:

分析

用regex配对,自己做的

DFS

找到数量相同的?和: 就可以开始切分dfs,参数是start and end

stack

遇到栈顶问号,就判断当前C是T/F,弹出4个,弹入结果

Last updated

Was this helpful?