题目:
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; } };
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