You've successfully subscribed to The Daily Awesome
Welcome back! You've successfully signed in.
Success! Your billing info is updated.
Billing info update failed.

5013. 字符串的索引对 - Index Pairs of a String

【字符串匹配】

Example:

输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]



输入: text = "ababa", words = ["aba","ab"]



1. 所有字符串都只包含小写字母。
2. 保证 words 中的字符串无重复。
3. 1 <= text.length <= 100
4. 1 <= words.length <= 20
5. 1 <= words[i].length <= 50
6. 按序返回索引对 [i,j]（即，按照索引对的第一个索引进行排序，当第一个索引对相同时按照第二个索引对排序）。

Analysis

!> 需要注意的是返回的结果需要排序

Solution 【字符串匹配】

class Solution {
public int[][] indexPairs(String text, String[] words) {
Stack<int[]> stack = new Stack<>();
for (String pattern : words) {
// System.out.println("\n" + text+"\t"+pattern);
int len = pattern.length();
int offset = 0;
int idx = text.indexOf(pattern);
while(idx != -1) {
// System.out.print(idx + " ");
int[] tmp = {idx, idx + len -1};
stack.push(tmp);
offset = idx + 1;
idx = text.indexOf(pattern, offset);

}
}
int[][] res = new int[stack.size()][2];
int i = 0;
for (int[] tmp : stack) {
res[i++] = tmp;
}
Arrays.sort(res, new Comparator<int[]>(){
@Override
public int compare(int[] a, int[] b) {
if (a[0] < b[0])
return -1;
else if (a[0] > b[0])
return 1;
else {
if (a[1] < b[1])
return -1;
else if (a[1] > b[1])
return 1;
}
return 0;
}
});
return res;
}
}