물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

243. Shortest Word Distance

BEstyle 2023. 3. 28. 18:53

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: 3

Example 2:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1

 

Constraints:

  • 2 <= wordsDict.length <= 3 * 104
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.
  • word1 != word2

class Solution:
    def shortestDistance(self, w: List[str], word1: str, word2: str) -> int:
        w1=[]
        w2=[]
        for i in range(len(w)):
            if w[i]==word1:
                w1.append(i)
            elif w[i]==word2:
                w2.append(i)
        print(w1,w2)
        cmin=float('inf')
        for n1 in w1:
            for n2 in w2:
                cmin=min(cmin,abs(n1-n2))
        return cmin

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

303. Range Sum Query - Immutable  (0) 2023.03.28
203. Remove Linked List Elements  (0) 2023.03.28
671. Second Minimum Node In a Binary Tree  (0) 2023.03.28
404. Sum of Left Leaves  (0) 2023.03.28
366. Find Leaves of Binary Tree  (0) 2023.03.23