将字符串拆分为其后缀数组的最有效方法是什么?
假设您有字符串“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
关于java - 如何将字符串拆分为后缀数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092630/