题目:
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.
HashMap。
C++版:
class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
unordered_map<string, vector<int>> d;
for(int i = 0; i < words.size(); i++) {
if(d.find(words[i]) == d.end()) {
vector<int> t(1, i);
d.insert(pair<string, vector<int>>(words[i], t));
} else
d[words[i]].push_back(i);
}
int s = INT_MAX;
for(auto i : d[word1]) {
for(auto j : d[word2]) {
int dis = abs(i - j);
if(dis < s)
s = dis;
}
}
return s;
}
};Python版:
import sys
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
d = {}
j = 0
for i in words:
if i not in d:
d[i] = [j]
else:
d[i].append(j)
j += 1
smallest = sys.maxint
for i in d[word1]:
for j in d[word2]:
distance = abs(i - j)
if distance < smallest:
smallest = distance
return smallest
这是一篇关于LeetCode第267题的解题报告,探讨如何找到给定单词列表中两个指定单词之间的最短距离。文章通过示例解释了问题,并提出了使用HashMap的数据结构来解决此问题的C++实现方案。

2065

被折叠的 条评论
为什么被折叠?



