Leetcode 243. Shortest Word Distance

Mingyu Jeon·2020년 5월 4일
0
post-thumbnail

#Runtime: 68 ms, faster than 57.47% of Python3 online submissions for Shortest Word Distance.
#Memory Usage: 17.4 MB, less than 12.50% of Python3 online submissions for Shortest Word Distance.
class Solution:
    def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
        keep1 = -1
        keep2 = -1
        ans = float(inf)
        for i in range(len(words)):
            if words[i] == word1:
                keep1 = i
            elif words[i] == word2:
                keep2 = i
            if keep1 >= 0 and keep2 >= 0:
                ans = min(ans, abs(keep1-keep2))
        return ans

https://leetcode.com/problems/shortest-word-distance/

0개의 댓글