c++ stack iterative solution, by ChaoyangHe


  • 1
        string parseTernary(string expression) {
            string result;
            const char* cstr = expression.c_str();
            int length = expression.size();
            stack<char> stk;
            for(int i = length -1; i >= 0; i--){
                char c = cstr[i];
                if(!stk.empty() && stk.top() == '?'){
                    stk.pop();
                    char left = stk.top();
                    stk.pop();
                    stk.pop();
                    char right = stk.top();
                    stk.pop();
                    if(c == 'T'){
                        stk.push(left);
                    }else{
                        stk.push(right);
                    }
                }else{
                   stk.push(c);
                }
            }
            result.push_back(stk.top());
            return result;
        }
    

Log in to reply
 

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