字符串的索引对 - 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 【字符串匹配】

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 `````` ``````class Solution { public int[][] indexPairs(String text, String[] words) { Stack 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(){ @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; } } ``````