Easy stack solution


  • 0
    T
    public class Solution {
        public string ParseTernary(string expression) {
            Stack<string> stack = new Stack<string>();
            stack.Push("");
            int len = expression.Length;
            
            int i = len-1;
            
            while(i >= 0){
                char c = expression[i];
                
                if(c == '?'){
                    i--;
                    
                    string s1 = stack.Pop();
                    string s2 = stack.Pop();
                    if(expression[i] == 'T'){
                        stack.Push(s1);
                    }else{
                        stack.Push(s2);
                    }
                }else if(c == ':'){
                    stack.Push("");
                }else{
                    stack.Push(c+stack.Pop());
                }
                i--;
            }
            
            return stack.Pop();
        }
    }
    

Log in to reply
 

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