LeetCode刷题实战243:最短单词距离
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
示例
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
解题
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;
}
};
赞 (0)