LC: 244. Shortest Word Distance II
https://leetcode.com/problems/shortest-word-distance-ii/
244. Shortest Word Distance II
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 betweenword1andword2in 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 1Constraints:
1 <= wordsDict.length <= 3 * 1041 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.word1 != word2At most
5000calls will be made toshortest.
The Essence:
Das Array words wird der Klasse zur Initialisierungszeit bereitgestellt. Das Verfahren kann also alle Indizes, die ein Wort hat, in eine Tabelle einfügen. Dann kann man nur diese Indizes anstatt des gesamten Arrays durchlaufen.
Damit zeigt das Problem, wie eine Vorverarbeitung bei der Lösung von Queryprobleme helfen kann.
Details:
Die Indizes eines Wortes können mit Hilfe einer Hash-Tabelle gespeichert werden. Beim Vergleich der Wörter nach ihren Indizes ist es hilfreich, zwei Zeiger zu verwenden, um diesmal den Index der Index-Liste zu speicher, da diese Liste sortiert ist. Ein negativer Abstand bedeutet, dass der erste Index steigen muss. Ein positiver Abstand weist darauf hin, dass der Index des zweiten Wortes erhöht werden muss, um dem Index des ersten zu entsprechen.
Solution(s) and Further Explanation:
Default Code:
Last updated