Leetcode 243 Solution
This article provides solution to leetcode question 243 (shortest-word-distance)
Access this page by simply typing in "lcs 243" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/shortest-word-distance
Solution
class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int j1 = -1;
int j2 = -1;
int min_dist = INT_MAX;
for (int i = 0; i < words.size(); i++)
{
if (word1 == words[i])
j1 = i;
else if (word2 == words[i])
j2 = i;
if (j1 != -1 && j2 != -1)
{
min_dist = min(min_dist, (int)abs(j1 - j2));
}
}
return min_dist;
}
};