本文主要是介绍LeetCode 题解(269) : Shortest Word Distance III,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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.
题解:
Python版:
import sysclass Solution(object):def shortestWordDistance(self, words, word1, word2):""":type words: List[str]:type word1: str:type word2: str:rtype: int"""d = {}j = 0for i in words:if i not in d:d[i] = [j]else:d[i].append(j)j += 1smallest = sys.maxintif word1 != word2:for i in d[word1]:for j in d[word2]:distance = abs(i - j)if distance < smallest:smallest = distanceelse:for i in range(len(d[word1])):for j in range(i + 1, len(d[word1])):distance = abs(d[word1][i] - d[word1][j])if distance < smallest:smallest = distancereturn smallest
这篇关于LeetCode 题解(269) : Shortest Word Distance III的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!