1. 题目
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-word-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
类似题目:
LeetCode 244. 最短单词距离 II(哈希map+set二分查找)
LeetCode 245. 最短单词距离 III
程序员面试金典 - 面试题 17.11. 单词距离(multimap平衡二叉搜索树)
class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int i1 = -1, i2 = -1, mindis = INT_MAX;
for(int i = 0; i < words.size(); ++i)
{
if(words[i] == word1)
i1 = i;
else if(words[i] == word2)
i2 = i;
if(i1 != -1 && i2 != -1)
mindis = min(mindis, abs(i1-i2));
}
return mindis;
}
};
20 ms 10.6 MB
长按或扫码关注我的公众号,一起加油、一起学习进步!