Java solution


  • 0
    M
    public String parseTernary(String expression) {
        char prev = 0;
        int i = 0;
        Stack<char[]> s = new Stack<>();
        int n = expression.length();
        while(i < n || !s.isEmpty()) {
            if(prev == 0) {
                char c = expression.charAt(i++);
                if(i == n || expression.charAt(i) == ':') {
                    prev = c;
                } else {
                    s.push(new char[]{c, 0, 0});
                }
                i++;
            } else {
                char[] e = s.peek();
                if(e[1] == 0) {
                    e[1] = prev;
                    prev = 0;
                } else {
                    s.pop();
                    prev = e[0] == 'T' ? e[1] : prev;
                }
            }
        }
        return Character.toString(prev);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.