Saturday, April 3, 2021

1249. Minimum Remove to Make Valid Parentheses

 Given a string s of '(' , ')' and lowercase English characters. 

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, contains only lowercase characters, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

 

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

 

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is one of  '(' , ')' and lowercase English letters.

class Solution {
public:
    string minRemoveToMakeValid(string s) {
        string ans;
        int start_count = 0;

        for (int i = 0; i < s.size(); i++) {
            if (s[i] != '(' && s[i] != ')') {
                ans += s[i];
                continue;
            }
            if (s[i] == '(') {
                start_count++;
                ans += s[i];
            } else {
                // It means S[i] == ')'
                if (start_count > 0) {
                    start_count--;
                    ans += s[i];
                }
            }
        }
        
        if (ans.size() == 0 || start_count == 0) {
            return ans;
        }
        // Remove extra start paren.
        // ans would 
        string new_ans;
        int iter = ans.size() - 1;
        int end_count = 0;
        while (iter >= 0) {
            if (ans[iter] != '(' && ans[iter] != ')') {
                new_ans += ans[iter];
                iter--;
                continue;
            }
            if (ans[iter] == ')') {
                end_count++;
                new_ans += ans[iter];
                iter--;
            } else {
                if (end_count > 0) {
                    end_count--;
                    new_ans += ans[iter];
                }
                iter--;
            }
        }
        
        reverse(new_ans.begin(), new_ans.end());
        return new_ans;
    }
};

No comments:

Post a Comment