0

我想要find all the substring一个字符串contains a key word

例如:“这是keyword字符串中的”。

输出:关键字,这是关键字,字符串中的关键字,...中的关键字。

我想先找到所有子字符串,然后尝试一个一个过滤。但我认为这将是一个非常糟糕的解决方案。

你能给我一些建议吗?非常感谢。

我已经编辑只是找到标记的序列。

4

2 回答 2

2

Try this:

String str = "abcdefkeybncv...";
String key = "key";
int index = str.indexOf(key);
ArrayList<String> sub = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
    for (int j = 0; j <= str.length() - i; j++) {
        String s = str.substring(i, i+j);
        if(s.indexOf(key) >= 0){
            sub.add(s);
        }
    }
}
System.out.println(sub);

Output for the code above:

[abcdefkey, abcdefkeyb, abcdefkeybn, abcdefkeybnc, abcdefkeybncv, abcdefkeybncv., abcdefkeybncv.., abcdefkeybncv..., bcdefkey, bcdefkeyb, bcdefkeybn, bcdefkeybnc, bcdefkeybncv, bcdefkeybncv., bcdefkeybncv.., bcdefkeybncv..., cdefkey, cdefkeyb, cdefkeybn, cdefkeybnc, cdefkeybncv, cdefkeybncv., cdefkeybncv.., cdefkeybncv..., defkey, defkeyb, defkeybn, defkeybnc, defkeybncv, defkeybncv., defkeybncv.., defkeybncv..., efkey, efkeyb, efkeybn, efkeybnc, efkeybncv, efkeybncv., efkeybncv.., efkeybncv..., fkey, fkeyb, fkeybn, fkeybnc, fkeybncv, fkeybncv., fkeybncv.., fkeybncv..., key, keyb, keybn, keybnc, keybncv, keybncv., keybncv.., keybncv...]
于 2013-08-21T18:57:11.343 回答
0
  1. 构建后缀数组:http ://en.wikipedia.org/wiki/Suffix_array
  2. 使用二进制搜索在那里找到您的子字符串
  3. 在后缀数组中从这一点上下移动,而后缀以子字符串开头
于 2013-08-21T19:21:03.177 回答