245. Shortest Word Distance III
Input: word1 = “makes”, word2 = “coding”
Output: 1Input: word1 = "makes", word2 = "makes"
Output: 3// Brute Force
int shortestWordDistance(vector<string>& words, string word1, string word2) { // time: O(n^2); space: O(1)
if (words.empty()) return 0;
int n = words.size(), res = INT_MAX;
for (int i = 0; i < n; ++i) {
if (words[i] != word1) continue;
for (int j = 0; j < n; ++j) {
if (words[j] != word2 || j == i) continue;
res = min(res, abs(i - j));
}
}
return res;
}Last updated