Facebook面试题 Remove unclosed parenthesis

本文介绍了一种算法,用于从含有括号的字符串中删除最少数量的字符以达到括号平衡的目的。该方法通过两次遍历字符串(从左到右及从右到左),确保保留尽可能多的有效括号对。

Given a String with parentheses, return a string with balanced parentheses by removing fewest characters possible. You cannot add anything to the string.
E.g.
balabce(“()”) -> “()”
balance(“)(“) -> “”
balance(“(((((()”) -> “()”
balance(“()(((()()”) -> “()()()”

  • Analysis:
    Obviously the requirement of this question is to delete all unclosed parentheses and reserve closed parentheses. At the same time, we need to close a right parenthesis with its nearest left parenthesis.
    The idea is like following:

    1. Traverse the string from left to right. Count the number of left and right parenthesis. If the number of right parenthesis is greater than the number of left parenthesis, delete the right parenthesis.
    2. Traverse the string from right to left. Count the number of left and right parenthesis. If the number of left parenthesis is greater than the number of right parenthesis, delete the left parenthesis.

    O(2n) = O(n) time, O(1) space. n is the length of the string.

Java implementation:

public class Solution {
    public String balance(String s) {
        int l = s.length();

        char[] chs = s.toCharArray();

        int L = 0;
        int R = 0;

        for (int i = 0; i < l; i++) {
            if (chs[i] == '(') L++;
            if (chs[i] == ')') R++;

            if (R > L) {
                chs[i] = '*';
                R--;
            }
        }

        L = 0;
        R = 0;

        for (int i = l - 1; i >= 0; i--) {
            if (chs[i] == ')') R++;
            if (chs[i] == '(') L++;

            if (L > R) {
                chs[i] = '*';
                L--;
            }
        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < l; i++) {
            if (chs[i] != '*') {
                sb.append(String.valueOf(chs[i]));
            }
        }

        return sb.toString();
    }
}

Github链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值