java - 解析嵌套数组字符串

标签 java arrays string multidimensional-array

我正在尝试将字符串中的任意嵌套数组解析为以下格式:[3,[4,3],5],为列表(列表,列表。 ..)

我的示例一旦解析,将是一个如下所示的列表:

List(3, List(4, 3), 5)

我写了一些代码(在这个问题的先前编辑中),但我的草稿都不起作用。我可以有一个示例实现或一些伪代码吗?

最佳答案

将嵌套数组解析为这样的字符串相当简单:

Arrays.deepToString(array).replace(" ", "");

将此字符串转换为无限嵌套列表有点棘手。最简单的解决方案可能是使用递归:

/**
 * The following code is only for demonstration purposes.
 * It does neither do any validation on the input String 
 * nor work with more than one digit numbers.
 */

static int index = 0; // the position in the String

Object buildList(String nestedList) {
    List<Object> list = new ArrayList<>();

    while (index < nestedList.length()) {
        char c = nestedList.charAt(index++);

        if (c == '[') // add a sub-list via a recursive call
                list.add(buildList(nestedList));
        else if (c == ']') // stop building the list
                 break;
        else if (c == ',') {} // do nothing
        else // add an element to the list
            list.add(c);
    }

    return list;
}

调用示例:

System.out.println(buildList("[3,[4,3],5]")); // prints [3, [4, 3], 5]


注意:

即使上面的代码实现了您想要实现的目标(至少我认为),但在实践中可能不建议使用这样的数据结构,因为对嵌套列表的访问非常复杂并且涉及一些类型转换。

更好的解决方案可能是使用某种树形数据结构,其中每个节点都有一个值列表,包括到其他节点的链接。 (参见:http://en.wikipedia.org/wiki/Tree_(data_structure))

关于java - 解析嵌套数组字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899052/

相关文章:

java - 执行基本 if else 语句时出现编译错误

java - 如何以 O(n) 的时间复杂度找到总和为 k 的所有子数组?

java - 获取 RESTEasy 实现中所有 Activity 的 Http Session

java - 如何计算字符串中每一行的字符并将数字转换为十六进制

javascript - 输入回文数

python - 如何从 Pandas 的 YYYY-YY 格式列中提取去年 (YYYY)

c# - 如何将纯文本json数据转成字符串?

java - 字符串不变性

java - 如何在 JasperReports 中指定断字

java - Java EE 5 API 的单个/完整 Maven 依赖项