我正在尝试将字符串中的任意嵌套数组解析为以下格式:[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/