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.
#1
Input: "F?1:T?4:5"

Output: "4"

Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:

             "(F ? 1 : (T ? 4 : 5))"                   "(F ? 1 : (T ? 4 : 5))"
          -> "(F ? 1 : 4)"                 or       -> "(T ? 4 : 5)"
          -> "4"                                    -> "4"

#2          
Input: "T?T?F:5:3"

Output: "F"

Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:

             "(T ? (T ? F : 5) : 3)"                   "(T ? (T ? F : 5) : 3)"
          -> "(T ? F : 3)"                 or       -> "(T ? F : 5)"
          -> "F"                                    -> "F"

? : 所组成的最小单位,可以看作一对括号。 ?类似(, :类似 )。
从左往右看,:作为决定一组完整最小单位的符号。每次找到一对就可以按:分为左右两个子问题递归解决。
宏观上看是从大到小拆开,从小到大递归回去。

public class Solution {
    public String parseTernary(String expression) {
        if(expression == null || expression.length() == 0){
            return expression;
        }
        char[] exp = expression.toCharArray();
        
        return DFS(exp, 0, exp.length - 1) + "";
        
    }
    public char DFS(char[] c, int start, int end){
        if(start == end){
            return c[start];
        }
        int count = 0, i =start;
        for(; i <= end; i++){
            if(c[i] == '?'){
                count ++;
            }else if (c[i] == ':'){
                count --;
                if(count == 0){
                    break;
                }
            }
        }
        return c[start] == 'T'? DFS(c, start + 2, i - 1) : DFS(c, i+1,end);
    }
}

从右往左看,? 作为决定最小单位的符号,每次遇到一个?, 就拆解离?最近的两个小单位。宏观上看是,从小到大。

public class Solution {
    public String parseTernary(String expression) {
        if(expression == null || expression.length() == 0) return "";
        Deque<Character> stk = new LinkedList<>();
        
        for(int i=expression.length()-1; i >= 0; i--){
            char c = expression.charAt(i);
            if(!stk.isEmpty() && stk.peek() == '?'){
                stk.pop();  // pop ?
                char first = stk.pop();
                stk.pop(); // pop :
                char second = stk.pop();
                
                if(c == 'T') stk.push(first);
                else stk.push(second);
            } else {
                stk.push(c);
            }
        }
        
        return String.valueOf(stk.peek());
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。