My C++ solution


  • 0
    M
    class Solution {
    public:
        string parseTernary(string expression) {
            return getTerm(0, expression.size(), expression);
        }
        
        string getTerm(int pos, int e, string &express) {
            if (pos >= e) return "";
            if (pos + 1 == e) return express.substr(pos, 1);
            bool verify = express[pos] == 'T';
            int pq = pos, pc = pos, num = 0;
            for (int i = pos; i < e; i++) {
                if (express[i] == '?') {
                    if (num == 0) pq = i;
                    ++num;
                } else if (express[i] == ':') {
                    if (num == 1) {
                        pc = i;
                        break;
                    }
                    --num;
                }
            }
            if (verify) {
                return getTerm(pq + 1, pc, express);
            }
            return getTerm(pc + 1, e, express);
        }
    };
    

Log in to reply
 

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