LeetCode 1065. Index Pairs of a String Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1065. Index Pairs of a String

Description

Given a string text and an array of strings words, return an array of all index pairs [i, j] so that the substring text[i...j] is in words.

Return the pairs [i, j] in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate).

 

Example 1:

Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
Output: [[3,7],[9,13],[10,17]]

Example 2:

Input: text = "ababa", words = ["aba","ab"]
Output: [[0,1],[0,2],[2,3],[2,4]]
Explanation: Notice that matches can overlap, see "aba" is found in [0,2] and [2,4].

 

Constraints:

  • 1 <= text.length <= 100
  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 50
  • text and words[i] consist of lowercase English letters.
  • All the strings of words are unique.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: words = set(words) n = len(text) return [ [i, j] for i in range(n) for j in range(i, n) if text[i : j + 1] in words ](code-box)

Solution 2

Python
class Trie: def __init__(self): self.children = [None] * 26 self.is_end = False def insert(self, word): node = self for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] node.is_end = True class Solution: def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: trie = Trie() for w in words: trie.insert(w) n = len(text) ans = [] for i in range(n): node = trie for j in range(i, n): idx = ord(text[j]) - ord('a') if node.children[idx] is None: break node = node.children[idx] if node.is_end: ans.append([i, j]) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !