首页 > 其他 > 详细

Leetcode 1249 移除无效的括号

时间:2020-12-25 23:42:57      阅读:32      评论:0      收藏:0      [点我收藏+]

技术分享图片

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

  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;
};

技术分享图片

Leetcode 1249 移除无效的括号

原文:https://www.cnblogs.com/niuyourou/p/14191029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!