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.

思路:用stack,判断是否match,set来收集不合法的右括号,最后留在stack里的是不合法的左括号,这样加起来就是需要delete的index,最后合成valid string就可以了。Time O(n) Space O(n);

class Solution {
    public String minRemoveToMakeValid(String s) {
        if(s == null || s.length() == 0) {
            return s;
        }
        Stack<Integer> stack = new Stack<Integer>();
        HashSet<Integer> skipSet = new HashSet<Integer>();
        
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '(') {
                stack.push(i);
            } else if(c == ')') {
                if(!stack.isEmpty()) {
                    stack.pop();
                } else {
                    // collect ')' index which needs to remove;
                    skipSet.add(i);
                }
            }
        }
        
        while(!stack.isEmpty()) {
            // collect '(' which needs to remove;
            skipSet.add(stack.pop());
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i++) {
            if(!skipSet.contains(i)) {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104731365