如何最有效地将字符串拆分为其后缀数组?
比如你有一个字符串"The weather is nice",我想生成一个如下的后缀数组:
[0] = "nice"
[1] = "is nice"
[2] = "weather is nice"
[3] = "the weather is nice"
我可以通过迭代器访问表单中的字符串,该迭代器从开始到结束依次遍历其标记(单词)。
使用 split
将数组按空格拆分,然后从后往前遍历结果标记。将当前标记添加到前一个后缀的开头。如果没有前缀,则使用空字符串:
String str = "quick brown fox jumps over the lazy dog";
List<String> res = new ArrayList<String>();
String last = null;
String[] tok = str.split(" ");
for (int i = tok.length-1 ; i >= 0 ; i--) {
if (last == null) {
last = tok[i];
} else {
last = tok[i] + " " + last;
}
res.add(last);
}
for (String s : res) {
System.out.println(s);
}
这将打印
dog
lazy dog
the lazy dog
over the lazy dog
jumps over the lazy dog
fox jumps over the lazy dog
brown fox jumps over the lazy dog
quick brown fox jumps over the lazy dog
ListArray<String>
中。然后从那里构建你的答案ListArray
,一点递归对灵魂有好处...
Iterable<String>
,如果您想要的话,我可以向您展示如何实现。 - jlordo