题目描述:
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
示例:
假设 words = [“practice”, “makes”, “perfect”, “coding”, “makes”]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = “makes”, word2 = “coding”
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
方法1:
主要思路:
(1)遍历一遍字典,出现相同的字符串时,更新可能存在的更小的距离;
class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
//存储两个字符串在字典中可能的位置
int index1=-1;
int index2=-1;
int res=words.size();//初始值置为不可能的最大值
for(int i=0;i<words.size();++i){
//出现相同的字符串时,更新可能的较小的距离
if(words[i]==word1){
index1=i;
if(index2!=-1){//另一个字符串出现过
res=min(res,abs(index1-index2));
}
}
else if(words[i]==word2){
index2=i;
if(index1!=-1){//另一个字符串出现过
res=min(res,abs(index1-index2));
}
}
}
return res;
}
};