LeetCode 243. 最短单词距离
给定一个字符串数组 wordDict
和两个已经存在于该数组中的不同的字符串 word1
和 word2
。返回列表中这两个单词之间的最短距离。
示例 1:
输入: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
输出: 3
示例 2:
输入: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
输出: 1
method
记录word1
和word2
出现时候的下标,保存两下标差绝对值的最小值
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
int res = INT_MAX;
int index1 = -1, index2 = -1;
for (int i = 0; i < wordsDict.size(); i++) {
if (wordsDict[i] == word1) index1 = i;
if (wordsDict[i] == word2) index2 = i;
if (index1 >= 0 && index2 >= 0) {
res = min(res, abs(index1 - index2));
}
}
return res;
}