LeetCode 0745. Prefix and Suffix Search Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0745. Prefix and Suffix Search

Description

Design a special dictionary that searches the words in it by a prefix and a suffix.

Implement the WordFilter class:

  • WordFilter(string[] words) Initializes the object with the words in the dictionary.
  • f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

 

Example 1:

Input
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output
[null, 0]
Explanation
WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".

 

Constraints:

  • 1 <= words.length <= 104
  • 1 <= words[i].length <= 7
  • 1 <= pref.length, suff.length <= 7
  • words[i], pref and suff consist of lowercase English letters only.
  • At most 104 calls will be made to the function f.

Solutions

Solution 1

PythonJavaC++Go
class WordFilter: def __init__(self, words: List[str]): self.d = {} for k, w in enumerate(words): n = len(w) for i in range(n + 1): a = w[:i] for j in range(n + 1): b = w[j:] self.d[(a, b)] = k def f(self, pref: str, suff: str) -> int: return self.d.get((pref, suff), -1) # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(pref,suff)(code-box)

Solution 2

PythonJavaGo
class Trie: def __init__(self): self.children = [None] * 26 self.indexes = [] def insert(self, word, i): 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.indexes.append(i) def search(self, pref): node = self for c in pref: idx = ord(c) - ord("a") if node.children[idx] is None: return [] node = node.children[idx] return node.indexes class WordFilter: def __init__(self, words: List[str]): self.p = Trie() self.s = Trie() for i, w in enumerate(words): self.p.insert(w, i) self.s.insert(w[::-1], i) def f(self, pref: str, suff: str) -> int: a = self.p.search(pref) b = self.s.search(suff[::-1]) if not a or not b: return -1 i, j = len(a) - 1, len(b) - 1 while ~i and ~j: if a[i] == b[j]: return a[i] if a[i] > b[j]: i -= 1 else: j -= 1 return -1 # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(pref,suff)(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 !