gpt4 book ai didi

java - 拆分递归组

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:26 25 4
gpt4 key购买 nike

我有一个以下格式的字符串:a,b,c[a,b,c[a]],d

(最终)我想要的结果是

a
b
c.a
c.b
c.c.a
d

关于如何完成这项任务有什么建议吗?

最佳答案

这是使用堆栈的可能解决方案。 (实现了 Avlin Bunk 的评论。)

public static Iterable<String> split(String s) {
List<String> result = new LinkedList<String>();
Stack<String> stack = new Stack<String>();
Pattern pattern = Pattern.compile("[,\\[\\]]|.+?");
Matcher matcher = pattern.matcher(s);

stack.push("");
while (matcher.find()) {
String token = matcher.group();
if (token.equals("[")) {
stack.push("");
} else if (token.equals("]")) {
if (! stack.peek().isEmpty())
result.add(join(".", stack));
stack.pop();
stack.pop();
stack.push("");
} else if (token.equals(",")) {
if (! stack.peek().isEmpty())
result.add(join(".", stack));
} else {
stack.pop();
stack.push(token);
}
}
if (! (stack.isEmpty() || stack.peek().isEmpty()))
result.add(join(".", stack));
return result;
}
<小时/>
public static String join(String sep, Iterable<String> it) {
// Return it[0] + sep + it[1] + sep + .... + it[lastIndex]
String joined = "";
boolean first = true;

for (String s : it) {
if (first)
first = false;
else
joined += sep;
joined += s;
}
return joined;
}

用法示例:

String text = "a,b,c[a,b,c[a]],d";
for (String s : split(text))
System.out.println(s);

参见Demo run .

( Same solution in Python , Recursive solution in Python )

关于java - 拆分递归组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21620183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com