什么是一个字符串分割成它的后缀数组的最有效方法是什么?如何将一个字符串拆分为一个后缀数组?
假设你有一个字符串“天气很好”,我想生成它的后缀数组作为这样的:
[0] = "nice"
[1] = "is nice"
[2] = "weather is nice"
[3] = "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
从,一点点递推是良好的灵魂..
调用.split(”“);将返回字符串中单词的数组。
它是否必须是一个数组?我会建议一个'可迭代',如果你想可以告诉你如何 –
jlordo
2013-02-26 15:22:44