Leetcode 245: Shortest Word Distance III

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

Shortest Word Distance III

Total Accepted: 1824 Total Submissions: 4282 Difficulty: Medium

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = "makes", word2 = "makes", return 3.

Note:
You may assume word1 and word2 are both in the list.

Code

import sys
class Solution(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        
        min_dis = sys.maxint
        p1, p2 = min_dis, -min_dis
        for i in xrange(len(words)):
            w = words[i]
            if w not in set([word1, word2]):
                continue
            if word1 == word2:
                p1 = p2
                p2 = i
            else:
                if w == word1:
                    p1 = i
                if w == word2:
                    p2 = i
           
            min_dis = min(min_dis, abs(p1 - p2))
        
        return min_dis

 

Idea

A little similar to the previous post. The only difference is that, if word1==word2, then we need to set `p1` to previous `p2`, and set `p2` to current `i`. We keep unchanged how `min_dis` is determined: min(min_dis, abs(p1 – p2)) 

 

Leave a comment

Your email address will not be published. Required fields are marked *