1、题目描述
2、解题思路
方法一:滑动窗口法
1、遍历 words 的每一个单词 word。定义窗口大小 windowSize = word.length();
2、遍历字符串 text:
2.1 如果 text.substring(i, i + windowSize) 和 word 一样,则保存一对索引 [i,i+i + windowSize - 1]
2.2 遍历的结束条件是:不满足 i <= text.length() - windowSize 则结束;
3、遍历完一个 word ,接着遍历下一个,知道遍历完所有的 word;
4、最终得到的 ans[][] 需要排序(提示的第 6 条有说明这个条件)
方法二:使用 indexOf 函数
text.indexOf(word)函数可以找到 word 在 text 中第一次出现的位置。
有了这个函数,就比直接手撕好多了,逻辑和方法一一样,直接看代码即可。
3、解题代码
class Solution {
public int[][] indexPairs(String text, String[] words) {
int windowSize;
List<Integer[]> lists = new ArrayList<>();
for (String word : words) {
windowSize = word.length();
for (int i = 0; i <= text.length() - windowSize; i++) {
if (word.equals(text.substring(i, i + windowSize))) {
Integer[] target = new Integer[2];
target[0] = i;
target[1] = i + windowSize - 1;
lists.add(target);
}
}
}
int[][] ans = new int[lists.size()][2];
for (int j = 0; j < lists.size(); j++) {
ans[j][0] = lists.get(j)[0];
ans[j][1] = lists.get(j)[1];
}
Arrays.sort(ans, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] != o2[0]) {
return o1[0] - o2[0];
} else {
return o1[1] - o2[1];
}
}
});
return ans;
}
}
import java.util.*;
class Solution {
public int[][] indexPairs(String text, String[] words) {
int wordLength;
List<Integer[]> lists = new ArrayList<>();
for (String word : words) {
wordLength = word.length();
int idx = text.indexOf(word);
while (idx != -1) {
Integer[] temp = {idx, idx + wordLength - 1};
lists.add(temp);
idx = text.indexOf(word, idx + 1);
}
}
int[][] ans = new int[lists.size()][2];
for (int j = 0; j < lists.size(); j++) {
ans[j][0] = lists.get(j)[0];
ans[j][1] = lists.get(j)[1];
}
Arrays.sort(ans, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
return ans;
}
}