|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +/** |
| 9 | + * 1056. Index Pairs of a String |
| 10 | + * |
| 11 | + * Given a text string and words (a list of strings), |
| 12 | + * return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] |
| 16 | + * Output: [[3,7],[9,13],[10,17]] |
| 17 | + * |
| 18 | + * Example 2: |
| 19 | + * Input: text = "ababa", words = ["aba","ab"] |
| 20 | + * Output: [[0,1],[0,2],[2,3],[2,4]] |
| 21 | + * Explanation: |
| 22 | + * Notice that matches can overlap, see "aba" is found in [0,2] and [2,4]. |
| 23 | + * |
| 24 | + * Note: |
| 25 | + * |
| 26 | + * All strings contains only lowercase English letters. |
| 27 | + * It's guaranteed that all strings in words are different. |
| 28 | + * 1 <= text.length <= 100 |
| 29 | + * 1 <= words.length <= 20 |
| 30 | + * 1 <= words[i].length <= 50 |
| 31 | + * Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate). |
| 32 | + * */ |
| 33 | +public class _1056 { |
| 34 | + public static class Solution1 { |
| 35 | + public int[][] indexPairs(String text, String[] words) { |
| 36 | + List<List<Integer>> lists = new ArrayList<>(); |
| 37 | + for (String word : words) { |
| 38 | + lists.addAll(findAllMatchsForThisWord(word, text)); |
| 39 | + } |
| 40 | + if (lists.isEmpty()) { |
| 41 | + return new int[][]{}; |
| 42 | + } |
| 43 | + Collections.sort(lists, (o1, o2) -> { |
| 44 | + if (o1.get(0) > o2.get(0)) { |
| 45 | + return 1; |
| 46 | + } else if (o1.get(0) < o2.get(0)) { |
| 47 | + return -1; |
| 48 | + } else { |
| 49 | + if (o1.get(1) > o2.get(1)) { |
| 50 | + return 1; |
| 51 | + } else { |
| 52 | + return -1; |
| 53 | + } |
| 54 | + } |
| 55 | + }); |
| 56 | + int[][] result = new int[lists.size()][lists.get(0).size()]; |
| 57 | + for (int i = 0; i < lists.size(); i++) { |
| 58 | + result[i][0] = lists.get(i).get(0); |
| 59 | + result[i][1] = lists.get(i).get(1); |
| 60 | + } |
| 61 | + return result; |
| 62 | + } |
| 63 | + |
| 64 | + private List<List<Integer>> findAllMatchsForThisWord(String word, String text) { |
| 65 | + List<List<Integer>> lists = new ArrayList<>(); |
| 66 | + for (int i = 0; i <= text.length() - word.length(); i++) { |
| 67 | + if (text.substring(i, i + word.length()).equals(word)) { |
| 68 | + lists.add(Arrays.asList(i, i + word.length() - 1)); |
| 69 | + } |
| 70 | + } |
| 71 | + return lists; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments