Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the WordDistance class:
WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.
The goal is to design a class that pre-processes the list of words to efficiently answer multiple queries about the shortest distance between two words.
Pre-processing:
Create a hash table to store the positions of each word in the array.
This facilitates quick lookups and distance calculations.
Calculating Distance:
For queries, retrieve the lists of positions for both words from the hash table.
Use two pointers to iterate through these lists and find the minimum distance between the positions.
classWordDistance:
def __init__(self, wordsDict: List[str]) ->None:
self.positions: Dict[str, List[int]] = defaultdict(list)
for index, word in enumerate(wordsDict):
self.positions[word].append(index)
defshortest(self, word1: str, word2: str) -> int:
pos1 = self.positions[word1]
pos2 = self.positions[word2]
i, j =0, 0 ans = float('inf')
while i < len(pos1) and j < len(pos2):
ans = min(ans, abs(pos1[i] - pos2[j]))
if pos1[i] < pos2[j]:
i +=1else:
j +=1return ans