c++ 8ms one pass recursive solution.


  • 0
    Z
    class Solution {
    public:
        string parseTernary(string e) {
            if (e.empty()) {
                return "";
            }
            if (e.size() == 1) {
                return e;
            }
            if (e[1] == ':') {
                return e.substr(0, 1);
            }
            if (e[0] == 'T') {
                return parseTernary(e.substr(2));
            } else if (e[0] == 'F') {
                int mat = 1;
                int i = 2;
                for (; i < e.size(); ++i) {
                    if (e[i] == '?') {
                        ++mat;
                    } else if (e[i] == ':') {
                        --mat;
                    }
                    if (mat == 0) break;
                }
                return parseTernary(e.substr(i + 1));
            } else {
                return e.substr(0, 1);
            }
        }
    };
    

Log in to reply
 

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