C++_26ms_Accepted_Stack


  • 0

    My solution could also solve input like: "F?739DHF : 37DJ2".

    class Solution {
    public:
    string parseTernary(string expression) {
        if(expression.empty()) return "";
        expression.push_back(':');
        int n = expression.size();
        stack<string> s;
        stack<char> opr;
        
        int i = 0;
        while(i < n){
            string tmp = "";
            while(expression[i] != ':' && expression[i] != '?'){
                tmp += expression[i];
                ++i;
            }
            if(tmp != ""){s.push(tmp);}
            
            if(expression[i] == '?'){opr.push('?');}
            else if(expression[i] == ':' && opr.top() == '?'){opr.push(':');}
            else{
                while(!opr.empty() && opr.top() == ':'){
                    string tmp2 = s.top(); s.pop();
                    string tmp1 = s.top(); s.pop();
                    opr.pop(), opr.pop();
                    tmp1 = s.top() == "T" ? tmp1 : tmp2;
                    s.pop();
                    s.push(tmp1);
                }
                opr.push(expression[i]);
            }
            ++i;
        }
        return s.top();
    }
    };

Log in to reply
 

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