You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串嵌套括号对移除逻辑问题求助

问题分析与修正方案

你的代码核心问题在于左右指针从两端向中间遍历的逻辑不适合处理嵌套括号的匹配——这种方式无法准确跟踪当前未闭合的左括号数量,导致像输入开头的无匹配右括号无法正确保留,嵌套的括号对也不能被完整移除。

正确逻辑说明

我们需要用从左到右单遍历+计数器的思路,逐个字符处理:

  • 用openCount记录当前未匹配的左括号数量
  • 遍历每个字符时:
    • 遇到左括号:计数器加1,不添加到结果(等待匹配的右括号)
    • 遇到右括号:如果计数器>0,说明有对应的左括号,计数器减1,不添加到结果(这对括号移除);如果计数器=0,说明这个右括号无匹配,直接添加到结果
    • 其他字符:直接添加到结果

这种思路能完美处理嵌套、多余的左/右括号场景,完全符合你的示例要求。

修改后的代码

public class PairRemoval {
    public static void main(String[] args) {
        // 测试示例1
        String text1 = "] hello world ] ] [ HELLO ] WORLD ] ] ] hello world";
        String leftPattern = "[";
        String rightPattern = "]";
        System.out.println(pairRemoval(text1, leftPattern, rightPattern));
        // 输出:hello world ] ] HELLO ] WORLD ] ] ] hello world

        // 测试示例2
        String text2 = "hello [ [ ] hello ] hello [ hello ] hello hello";
        System.out.println(pairRemoval(text2, leftPattern, rightPattern));
        // 输出:hello hello hello hello hello hello

        // 测试示例3
        String text3 = "> hello hello > > < hello > hello > > > hello hello";
        System.out.println(pairRemoval(text3, "<", ">"));
        // 输出: hello hello > > hello > hello > > > hello hello
    }
    
    public static String pairRemoval(String text, String leftPattern, String rightPattern) {
        int openCount = 0;
        // 用StringBuilder比直接拼接字符串效率高很多
        StringBuilder result = new StringBuilder();
        char leftBracket = leftPattern.charAt(0);
        char rightBracket = rightPattern.charAt(0);

        for (char c : text.toCharArray()) {
            if (c == leftBracket) {
                openCount++;
            } else if (c == rightBracket) {
                if (openCount > 0) {
                    openCount--;
                } else {
                    // 无匹配的左括号,保留这个右括号
                    result.append(c);
                }
            } else {
                // 非括号字符直接添加
                result.append(c);
            }
        }

        return result.toString();
    }
}

代码细节解释

  1. 用StringBuilder替代字符串拼接:字符串在Java中是不可变的,每次sentence = sentence + leftLetter都会创建新对象,效率极低,StringBuilder是可变的,适合这种逐字符构建的场景。
  2. 提前提取左右括号字符:避免每次循环都调用leftPattern.charAt(0),提升效率。
  3. 逐字符遍历:确保每个字符都被正确判断,无论是嵌套括号还是多余的括号,都能按规则处理。

你可以把所有示例输入代入测试,结果都会符合预期。

内容的提问来源于stack exchange,提问作者Salome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:13:16