https://leetcode.com/problems/shortest-word-distance/
Shortest Word Distance
Total Accepted: 2492 Total Submissions: 5946 Difficulty: Easy
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “coding”
, word2 = “practice”
, return 3.
Given word1 = "makes"
, word2 = "coding"
, return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Code
import sys class Solution(object): def shortestDistance(self, words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ p1 = p2 = -1 min_dis = sys.maxint for i in xrange(len(words)): w = words[i] if w not in [word1, word2]: continue if w == word1: p1 = i if w == word2: p2 = i if p1 != -1 and p2 != -1: min_dis = min(min_dis, abs(p1 - p2)) return min_dis
Idea
Just need O(N) time to traverse the `word` list once. `p1` and `p2` are the last index of seeing word1 and word2. If the current visit word is either word1 or word2, you can update the min distance just by `abs(p1-p2)`.