Leetcode 1249 移除无效的括号

  括号先后成对出现,适合使用栈结构进行处理。

  JAVA :

public final String minRemoveToMakeValid(String s) {
        if (s == null || s.length() == 0) return "";
        StringBuilder sb = new StringBuilder();
        Stack<Integer> stack = new Stack<Integer>();
        int len = s.length();
        char[] sChar = s.toCharArray();
        for (int i = 0; i < len; i++) {
            if (sChar[i] == '(') stack.push(i);
            else if (sChar[i] == ')') {
                if (!stack.empty()) stack.pop();
                else sChar[i] = '-';
            }
        }
        for (Integer prePoint : stack) sChar[prePoint] = '-';
        for (int i = 0; i < len; i++) {
            if (sChar[i] != '-') sb.append(sChar[i]);
        }
        return sb.toString();
    }

  JS:

var minRemoveToMakeValid = function (s) {
    let stack = [], len = s.length, sChar = s.split('');
    for (let i = 0; i < len; i++) {
        if (sChar[i] == '(') stack.push(i);
        else if (sChar[i] == ')') {
            if (stack.length == 0) sChar[i] = '-';
            else stack.pop();
        }
    }
    for (let i = 0; i < stack.length; i++) sChar[stack[i]] = '-';
    s = sChar.join('');
    s = s.replace(/-/g, '');
    return s;
};

posted @ 2020-12-25 22:36  牛有肉  阅读(124)  评论(0编辑  收藏  举报