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 arraywordsDict
.int shortest(String word1, String word2)
returns the shortest distance betweenword1
andword2
in the arraywordsDict
.
Example 1:
Input ["WordDistance", "shortest", "shortest"] [[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]] Output [null, 3, 1] Explanation WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]); wordDistance.shortest("coding", "practice"); // return 3 wordDistance.shortest("makes", "coding"); // return 1
Constraints:
1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i]
consists of lowercase English letters.word1
andword2
are inwordsDict
.word1 != word2
- At most
5000
calls will be made toshortest
.
class WordDistance:
def __init__(self, wordsDict: List[str]):
self.words = {}
for i, word in enumerate(wordsDict):
indexes = self.words.get(word, [])
indexes.append(i)
self.words[word] = indexes
def shortest(self, word1: str, word2: str) -> int:
idx1, idx2 = self.words[word1], self.words[word2]
i1 = i2 = 0
shortest = float('inf')
while i1 < len(idx1) and i2 < len(idx2):
shortest = min(shortest, abs(idx1[i1] - idx2[i2]))
smaller = idx1[i1] < idx2[i2]
if smaller:
i1 += 1
else:
i2 += 1
return shortest
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
class WordDistance {
private Map<String, List<Integer>> words;
public WordDistance(String[] wordsDict) {
words = new HashMap<>();
for (int i = 0; i < wordsDict.length; ++i) {
words.computeIfAbsent(wordsDict[i], k -> new ArrayList<>()).add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> idx1 = words.get(word1);
List<Integer> idx2 = words.get(word2);
int i1 = 0, i2 = 0, shortest = Integer.MAX_VALUE;
while (i1 < idx1.size() && i2 < idx2.size()) {
shortest = Math.min(shortest, Math.abs(idx1.get(i1) - idx2.get(i2)));
boolean smaller = idx1.get(i1) < idx2.get(i2);
if (smaller) {
++i1;
} else {
++i2;
}
}
return shortest;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/