码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 1249 移除无效的括号

时间:2020-12-31 11:42:50      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ali   tac   string   char   info   ack   java   移除   cti   

技术图片

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

  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 移除无效的括号

标签:ali   tac   string   char   info   ack   java   移除   cti   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!