题目
给定一个较长字符串
big
和一个包含较短字符串的数组smalls
,设计一个方法,根据smalls
中的每一个较短字符串,对big
进行搜索。输出smalls
中的字符串在big
里出现的所有位置positions
,其中positions[i]
为smalls[i]
出现的所有位置。示例:
输入: big = "mississippi" smalls = ["is","ppi","hi","sis","i","ssippi"] 输出: [[1,4],[8],[],[3],[1,4,7,10],[5]]提示:
0 <= len(big) <= 1000
0 <= len(smalls[i]) <= 1000
smalls
的总字符数不会超过 100000。- 你可以认为
smalls
中没有重复字符串。- 所有出现的字符均为英文小写字母。
AC代码
class Solution {
public int[][] multiSearch(String big, String[] smalls) {
int[][] ret = new int[smalls.length][];
for (int i = 0; i < smalls.length; i++) {
ArrayList<Integer> count = new ArrayList<>();
String str = smalls[i];
if (str.isEmpty()) {
ret[i] = new int[0];
continue;
}
int[] next = getNext(str);
int posBig = 0;
int posSmall = 0;
while (posBig < big.length()) {
while (posSmall > 0 && big.charAt(posBig) != str.charAt(posSmall)) {
posSmall = next[posSmall - 1];
}
if (big.charAt(posBig) == str.charAt(posSmall)) {
if (posSmall == str.length() - 1) {
count.add(posBig - str.length() + 1);
posSmall = -1;
posBig = posBig - str.length() + 1;
}
posSmall++;
}
posBig++;
}
ret[i] = new int[count.size()];
for (int j = 0; j < count.size(); j++) {
ret[i][j] = count.get(j);
}
}
return ret;
}
private int[] getNext(String pattern) {
int[] ret = new int[pattern.length()];
int j = 0;
for (int i = 1; i < pattern.length(); i++) {
if (pattern.charAt(i) == pattern.charAt(j)) {
j++;
} else {
while (j > 0 && pattern.charAt(i) != pattern.charAt(j)) {
j = ret[j - 1];
}
}
ret[i] = j;
}
return ret;
}
}