【Lintcode】2506. Remove the Invalid Parentheses

题目地址:

https://www.lintcode.com/problem/2506/description

给定一个含小括号的字符串 s s s(也可能含别的字符,但不会含别的类型的括号),问至少删除多少个括号可以使得 s s s中的括号序列是合法的。返回任一删除多余括号之后的合法答案即可。

可以开一个栈存下标,当新来的右括号没有左括号匹配的时候(对应栈空)则将其标记为要删除,最后如果栈不空,将栈里的下标标记为要删除。这样就得到了所有要删除的括号的下标。代码如下:

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution {
    /**
     * @param s: A string with lowercase letters and parentheses
     * @return: A string which has been removed invalid parentheses
     */
    public String removeParentheses(String s) {
        // write your code here.
        char[] chs = s.toCharArray();
        Deque<Integer> stk = new ArrayDeque<>();
        for (int i = 0, cnt = 0; i < chs.length; i++) {
            if (chs[i] == '(') {
                stk.push(i);
                cnt++;
            } else if (chs[i] == ')') {
                if (cnt == 0) {
                	// 标记为空字符,表示要删除
                    chs[i] = ' ';
                } else {
                    cnt--;
                    stk.pop();
                }
            }
        }
        while (!stk.isEmpty()) {
            chs[stk.pop()] = ' ';
        }
        
        StringBuilder sb = new StringBuilder();
        for (char ch : chs) {
            if (ch != ' ') {
                sb.append(ch);
            }
        }
        
        return sb.toString();
    }
}

时空复杂度 O ( l s ) O(l_s) O(ls)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值