244. Shortest Word Distance II
LeetCode 244. Shortest Word Distance II
Description
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:
Constraints:
1 <= wordsDict.length <= 3 * 10^4
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
.
Tags
Design, Hash Table, Binary Search
Solution
Build a hash table mapping from word to its indices list. For faster distance search, we perform binary search on one of the lists.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?