Simple C++ Stack Solution with comments.


  • 0
    F
    class Solution {
    public:
        string parseTernary(string exp) {
            stack<string> vals;
            string curval;
            for (int i = 0; i < exp.size(); ++ i)
            {
                if (exp[i] != '?' && exp[i] != ':')
                {
                    curval.push_back(exp[i]);
                    continue;
                }
                if (exp[i] == ':')
                {
                    int colonskip = 0;
                    while (vals.size() && vals.top() == "T")
                    {
                        colonskip ++; //Count how many T we popped. One T means we can skip one colon later 
                        vals.pop();  //because T's after-colon value should be discarded
                    }
                    if (vals.empty()) 
                        return curval;
                    vals.pop(); //Now it meets a F, we need skip all colons until after this F's colon
                    while (colonskip > 0) //This loop is to skip the colons.
                    {
                        i ++;
                        if (exp[i] == ':')
                            colonskip --;
                        if (exp[i] == '?')
                            colonskip ++;
                    }
                    curval.clear();
                }
                if (exp[i] == '?')
                {
                    vals.push(curval);
                    curval.clear();
                }
            }
            return curval;
        }
    };
    

Log in to reply
 

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