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

如何查找字符串中第一个非嵌套最外层括号的索引?

找出字符串中第一个最外层(非嵌套)括号的索引

需求说明

我们需要实现一个功能:定位字符串中第一个最外层(非嵌套)括号的起始和结束索引。这里的最外层括号指的是从第一个[开始,匹配到对应的闭合]——中间的嵌套括号不会被当作外层的结束标志。

示例展示

  • 输入 [],输出:0, 1
  • 输入 1[2],输出:1, 3
  • 输入 3[a2[c]]2[abc]3[cd],输出:1, 7

实现代码

下面是基于计数法的Java实现代码:

public static void main(String[] args) {
    String input = "3[a2[c]]2[abc]3[cd]ef";
    int first = 0;
    int second = 0;
    int count = 0;
    boolean found = false;
    for (int index = 0; index < input.length(); index++) {
        if (input.charAt(index) == '[') {
            count++;
            if (!found) {
                found = true;
                first = index;
            }
        } else if (input.charAt(index) == ']') {
            count--;
            if (count == 0 && found) {
                second = index;
                break;
            }
        }
    }
    System.out.println("第一个最外层括号的索引:" + first + ", " + second);
}

代码思路解析

  • 用count变量跟踪括号的嵌套层级:遇到[就加1,遇到]就减1
  • found标记用来记录是否已找到第一个外层的[
  • 第一次遇到[时,记录它的索引到first,并将found设为true
  • 后续每遇到]就减少计数,当计数回到0时,说明找到了对应的外层闭合],记录其索引到second后直接跳出循环(因为我们只需要第一个最外层括号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:34:37