1249. Minimum Remove to Make Valid Parentheses

23 阅读1分钟

image.png

方法

  • 先便利一遍字符串,只看字符为 ( ) 的, 用stack来抵消括号,记录非法括号的index
  • 跳过非法index,构造字符串
class Solution {
    public String minRemoveToMakeValid(String s) {
        Stack<Integer> stack = new Stack<>(); // 用于括号匹配
        Set<Integer> set = new HashSet<>(); // index of chars to remove
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else if (c == ')') {
                if (stack.isEmpty()) {
                    set.add(i);// 非法 )
                } else {
                    stack.pop();
                }
            }
        }
        // 剩余的括号都不合法,应该删除
        while (!stack.isEmpty()) {
            set.add(stack.pop());
        }

        // build new string,跳过非法的括号index
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!set.contains(i)) {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}