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

如何在O(nlogn)时间内将字符串转换为Java二维数组?

解决方案:将指定格式字符串转为二维int数组

问题分析

你当前代码的核心问题是split("[")用法错误——[是正则表达式的特殊元字符,直接使用会触发语法错误,必须用双反斜杠\\[转义。即便转义,这种分割方式也会产生大量空字符串,后续处理效率极低。另外,你需要避免多层循环,同时保证转换过程时间复杂度不超过O(nlogn)(实际转换可做到O(n),完全符合要求)。

高效实现代码(使用流API,无显式多层循环)

以下方案通过Java流API处理,既避免了显式多层循环,又保证了线性时间复杂度:

import java.util.Scanner;
import java.util.Arrays;

public class StringTo2DArray {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        
        // 清理字符串:移除首尾[],清除所有空格
        String cleaned = input.trim().substring(1, input.length() - 1).replaceAll("\\s+", "");
        
        // 分割为子数组字符串
        String[] subArrayStrs = cleaned.split("\\],\\[");
        
        // 流式转换为二维int数组
        int[][] result = Arrays.stream(subArrayStrs)
                .map(subStr -> Arrays.stream(subStr.split(","))
                        .mapToInt(Integer::parseInt)
                        .toArray())
                .toArray(int[][]::new);
        
        // 验证输出
        for (int[] row : result) {
            System.out.println(Arrays.toString(row));
        }
    }
}

代码说明

  • 字符串清理:先截断首尾的[],再用replaceAll("\\s+", "")清除所有空格,避免空格干扰分割逻辑。
  • 子数组分割:用\\],\\[作为分隔符(转义特殊字符),直接得到每个子数组的纯数字字符串。
  • 流转换:通过两层流操作完成类型转换,内部遍历为线性操作,整体时间复杂度O(n)(n为所有数字总个数),远低于要求的O(nlogn)。

替代方案(无流API,单显式循环)

如果偏好不用流API,可通过单循环结合索引处理,同样避免多层显式循环:

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class StringTo2DArray {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine().trim();
        
        List<List<Integer>> tempList = new ArrayList<>();
        List<Integer> currentRow = new ArrayList<>();
        StringBuilder numBuilder = new StringBuilder();
        
        // 遍历字符串,跳过首尾的[]
        for (int i = 1; i < input.length() - 1; i++) {
            char c = input.charAt(i);
            if (c == ',' || c == ']') {
                if (numBuilder.length() > 0) {
                    currentRow.add(Integer.parseInt(numBuilder.toString()));
                    numBuilder.setLength(0);
                }
                if (c == ']') {
                    tempList.add(currentRow);
                    currentRow = new ArrayList<>();
                    // 跳过下一个[
                    i++;
                }
            } else if (Character.isDigit(c) || c == '-') { // 兼容负数场景
                numBuilder.append(c);
            }
            // 自动忽略空格
        }
        
        // 转换为二维int数组
        int[][] result = new int[tempList.size()][];
        for (int i = 0; i < tempList.size(); i++) {
            List<Integer> row = tempList.get(i);
            result[i] = row.stream().mapToInt(Integer::intValue).toArray();
        }
        
        // 验证输出
        for (int[] row : result) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}

该方案仅用一层显式循环遍历字符串,时间复杂度仍为O(n),完全符合你的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:20:28