Shortest Word Distance
Problem
Given an array of strings wordsDict
and two different strings that already exist in the array word1
and word2
, return the shortest distance between these two words in the list.
Constraints
2 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i]
consists of lowercase English letters.word1
andword2
are inwordsDict
.word1 != word2
Solution
The problem Shortest Word Distance
can be solved by recording indexes for appearances of word1
or word2
in wordsDict
and finding smallest distance between those indexes.
Implementation
class Solution
{
public:
int shortestDistance(vector<string> &wordsDict, string word1, string word2)
{
int ret = INT_MAX;
int idx1 = -1, idx2 = -1;
for (int i = 0; i < wordsDict.size(); i++)
{
if (wordsDict[i] == word1)
idx1 = i;
else if (wordsDict[i] == word2)
idx2 = i;
if (idx1 != -1 && idx2 != -1)
ret = min(ret, abs(idx1 - idx2));
}
return ret;
}
};