java 439.三元表达式Parser.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 439.三元表达式Parser.java相关的知识,希望对你有一定的参考价值。

/*
In order to pick out useful "?" and ":", we can always begin with the last "?" and the first ":" after the chosen "?".
Therefore, directly seek for the last "?" (or you can simply put all "?" into a stack) and update the string depending on T or F until no more "?"s.
*/

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

以上是关于java 439.三元表达式Parser.java的主要内容,如果未能解决你的问题,请参考以下文章

java 439.三元表达式Parser.java

java 439.三元表达式Parser.java

java 439.三元表达式Parser.java

java 439.三元表达式Parser.java

java三元表达式怎么算

java 三元运算