[LeetCode] Shortest Word Distance

243. Shortest Word Distance

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
int a = -1, b = -1, res = INT_MAX;
for(int i = 0; i < wordsDict.size(); i++) {
if(wordsDict[i] == word1) a = i;
if(wordsDict[i] == word2) b = i;
if(a != -1 and b != -1) res = min(res, abs(a-b));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/16/PS/LeetCode/shortest-word-distance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.