题目来源
题目描述
请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。
示例:
假设 words = [“practice”, “makes”, “perfect”, “coding”, “makes”]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
class WordDistance {
public:
WordDistance(vector<string>& words) {
}
int shortest(string word1, string word2) {
}
private:
};
题目解析
思路
- 用一个map来建立每个单词与其所有出现的位置的映射
- 当需要最短单词距离时,只需要取出该单词在map中映射的数组进行两两比较即可
实现
class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int res = INT32_MAX;
for (int i = 0; i < m[word1].size(); ++i) {
for (int j = 0; j < m[word2].size(); ++j) {
res = min(res, abs(m[word1][i] - m[word2][j]));
}
}
return res;
}
private:
std::unordered_map<std::string, std::vector<int>> m;
};
优化
- 用两个指针i和j来指向位置数组中的某个元素,开始时均初始化为0
- 然后比较位置数组中的数字,将较小的一个指针向后移动一位,直到其中一个数组遍历完成即可
- 时间复杂度O(M + N),其中M和N为两个单词的长度
class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
int res = INT32_MAX, i = 0, j = 0;
while (i < m[word1].size() && j < m[word2].size()){
res = min(res, abs(m[word1][i] - m[word2][j]));
m[word1][i] < m[word2][j] ? ++i : ++j;
}
return res;
}
private:
std::unordered_map<std::string, std::vector<int>> m;
};
类似题目
题目 | |
---|---|
leetcode:243. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词不同,只调用一次) | 想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离: 用两个变量 p1,p2 初始化为 -1,然后遍历数组,遇到单词1,就将其位置存在 p1 里,若遇到单词2,就将其位置存在 p2 里,如果此时 p1, p2 都不为 -1 了,那么更新结果 |
leetcode:244. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词不同,需要调用多次) | 想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离:用一个map来建立每个单词与其所有出现的位置的映射。 |
leetcode:245. 单词列表中某两个单词的最短距离 Shortest Word Distance (两个单词可能相同,需要调用多次) | 想办法定位 word1 word2 在数组中的位置, 然后计算其相对距离: 三指针 |
leetcode:21. 合并两个有序链表 Merge Two Sorted Lists | 用两个指针分别执行两个链表,哪个小就移动哪个指针 |