class Solution(object):
    def shortestDistance(self, wordsDict, word1, word2):
        """
        :type wordsDict: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        w1_list = []
        w2_list = []
        for idx in range(len(wordsDict)):
            if wordsDict[idx] == word1:
                w1_list.append(idx)
            elif wordsDict[idx] == word2:
                w2_list.append(idx)
            else:
                continue
                

        smaller = w1_list
        bigger = w2_list
        ans = abs(bigger[0] - smaller[0])
        
        while bigger and smaller:
            if bigger[0] < smaller[0]:
                temp = bigger
                bigger = smaller
                smaller = temp
            temp = bigger[0] - smaller[0]
            if temp == 1:
                return 1
            elif temp < ans:
                ans = temp
                smaller.pop(0)
            else:
                smaller.pop(0)
        
        return ans 
	
Comments (1)
No comments yet.