C++ version of the correct java version written here


  • 0
    Z

    string reverser(string s) {
    for (int i = 0; i < s.size()/ 2; i++) {
    char temp = s[i];
    s[i] = s[s.size() - 1 - i];
    s[s.size() - 1 - i] = temp;
    }
    return s;
    }

    void helper(string s, int l, int r, vector<string>& ans, string X){

    int stack = 0;
    for (int i =l; i < s.length(); i++) {
        if (s[i] == X[0])
            stack ++;
        if (s[i] == X[1])
            stack --;
        if (stack >= 0)
            continue;
    
        for (int j = r; j <= i; j++  ) {
            if (s[j] == X[1] && (j == r || s[j-1] != X[1])  ) {
                 helper(s.substr(0, j) + s.substr(j+1, s.length() -1), i, j, ans, X);
            }
        }
        return;
    }
    
    // Now check the reverse string.
    string rs = reverser(s);
    if (X[0] == '(') {
        helper(rs, 0, 0, ans, ")(");
    } else
        ans.push_back(rs);
    

    }
    class Solution {
    public:
    vector<string> removeInvalidParentheses(string s) {
    vector<string> ans;
    helper(s, 0, 0, ans, "()");
    return ans;
    }
    };


Log in to reply
 

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