Index Pairs of a String
给一个字符串text, 给一组字符串wrods, 问找到这组字符串中每个元素在text中的位置. 这个题就用indexof找就可以, indexof的第二个参数可以是startIndex.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public int[][] indexPairs(String text, String[] words) { List<int[]> list = new ArrayList<>(); for(String w : words) { int i = 0; while(i < text.length()){ int j = text.indexOf(w, i); if(j == -1) break; list.add(new int[]{j, j + w.length() - 1}); j++; i = j; } } list.sort((a, b) -> a[0] - b[0] == 0 ? (a[1] - b[1]) : (a[0] - b[0])); int[][] res = new int[list.size()][2]; for(int i = 0; i < list.size(); i++) { res[i] = list.get(i); } return res; } } |