题目来源
题目描述
题目:
给定一个字符串数组 wordsDict 和两个字符串 word1 和 word2 ,返回列表中这两个单词之间的最短距离。
示例 :
输入:wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”],
word1 = “makes”, word2 = “coding”
输出:1
word1 = “makes”, word2 = “makes”
输出:3
注意:word1 和 word2 是有可能相同的,并且它们将分别表示为列表中 两个独立的单词 。
实现
核心思路
思路还是:想办法定位 word1 word2 在数组中的位置(有两张情况, 需要分开处理~), 计算其相对距离, 求出其最短即可
难点:怎么处理单词相同的情况
思路
- 用两个变量 p1,p2 初始化为 -1,然后遍历数组,遇到单词1,就将其位置存在 p1 里,若遇到单词2,就将其位置存在 p2 里
- 由于p1和p2可能会相同,所以需要一个遍历t来记录上一个单词的位置,这样如果t不为 -1,且和当前的 p1 不同,可以更新结果,如果 word1 和 word2 不等,那么还是按原来的方法做,
实现
class Solution {
public:
int shortestWordDistance(vector<string>& words, string word1, string word2) {
int p1 = -1, p2 = -1, res = INT_MAX;
for (int i = 0; i < words.size(); ++i) {
int t = p1;
if (words[i] == word1) p1 = i;
if (words[i] == word2) p2 = i;
if (p1 != -1 && p2 != -1) {
if (word1 == word2 && t != -1 && t != p1) {
res = min(res, abs(t - p1));
} else if (p1 != p2) {
res = min(res, abs(p1 - p2));
}
}
}
return res;
}
};
思路
- 只用一个变量 idx,这个 idx 的作用就相当于记录上一次的位置
- 当前 idx 不等 -1 时,说明当前i和 idx 不同,然后在 word1 和 word2 相同或者 words[i] 和 words[idx] 相同的情况下更新结果,最后别忘了将 idx 赋为i
class Solution {
public:
int shortestWordDistance(vector<string>& words, string word1, string word2) {
int idx = -1, res = INT32_MAX;
for (int i = 0; i < words.size(); ++i) {
if(words[i] == word1 || words[i] == word2){
if (idx != -1 && (word1 == word2 || words[i] != words[idx])) {
res = min(res, i - idx);
}
idx = i;
}
}
return res;
}
private:
};
类似题目
题目 | |
---|---|
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 在数组中的位置, 然后计算其相对距离: 三指针 |