LC: 243. Shortest Word Distance
https://leetcode.com/problems/shortest-word-distance/
243. Shortest Word Distance
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.
Example 1:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3Example 2:
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1Constraints:
1 <= wordsDict.length <= 3 * 1041 <= wordsDict[i].length <= 10wordsDict[i]consists of lowercase English letters.word1andword2are inwordsDict.word1 != word2
The Essence:
Wir müssen berücksichtigen, dass diese 2 Wörter mehrmals vorkommen können. Es kann also mehrere Abstände geben.
Details:
Wir sollen den letzten Index der Wörter speichern und den Abstand rechnen, wenn ein dieser Wörter auftritt. Wenn dieser Abstand kürzer als der vorher Gerechnete ist, dann wird es der Kürzeste. Der Vergleich kann man in Java mit der Methode Math.min() machen.
Solutions:
Default code:
Last updated