给出一个单词列表和两个单词单词1,单词2,返回列表中这两个单词之间的最短距离。
样例
样例 1:
输入:["practice", "makes", "perfect", "coding", "makes"],"coding","practice"
输出:3
解释:index("coding") - index("practice") = 3
样例 2:
输入:["practice", "makes", "perfect", "coding", "makes"],"makes","coding"
输出:1
解释:index("makes") - index("coding") = 1
注意事项
您可以假定单词1不等于单词2,而单词1和单词2在列表中都存在。
class Solution {
public:
/**
* @param words: a list of words
* @param word1: a string
* @param word2: a string
* @return: the shortest distance between word1 and word2 in the list
*/
int shortestDistance(vector<string> &words, string &word1, string &word2) {
// Write your code here
int index1=-1;
int index2=-1;
int mins=words.size();
for (int i = 0; i < words.size(); i++) {
/* code */
if(words[i]==word1) index1=i;
else if(words[i]==word2) index2=i;
else continue;
if(index1>=0&&index2>=0) mins=min(mins,abs(index2-index1));
}
return mins;
}
};