6ms C++ solution, Easy to understand.


  • 0
    C

    The algorithm is clear. And the implement is easy to understand, though a little redundant.

    class Solution {
    public:
        string parseTernary(string expression) {
            if (expression.find('?') == string::npos) return expression;
            if (expression[0] == 'T'){
                    int divide = find_divide(expression.substr(2,expression.size() - 2));
                    return parseTernary(expression.substr(2,divide));
            }
            else if (expression[0] == 'F'){
                int divide = find_divide(expression.substr(2,expression.size() - 2));
                return parseTernary(expression.substr(divide+3,expression.size()-divide-3));
            }
        }
        int find_divide(string input){
            int flag = 0;
            for (int i = 0; i < input.size();i++){
                if (input[i] == '?') flag ++;
                else if (input[i] == ':') flag --;
                if (flag < 0) return i;
            }
            return input.size();
        }
    };
    

Log in to reply
 

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