◻️924. Shortest Word Distance (easy)
Input:["practice", "makes", "perfect", "coding", "makes"],"coding","practice"
Output:3
Explanation:index("coding") - index("practice") = 3Input:["practice", "makes", "perfect", "coding", "makes"],"makes","coding"
Output:1
Explanation:index("makes") - index("coding")Solutions
Optimised
class Solution {
public:
/**
* @param words: a list of words
* @param word1: a string
* @param word2: a string
* @return: the shortest distance between word1 and word2 in the list
*/
int shortestDistance(vector<string> &words, string &word1, string &word2) {
int ans = INT_MAX;
for (int k = 0, i = -1, j = -1; k < words.size(); ++k) {
if (words[k] == word1) {
i = k;
}
if (words[k] == word2) {
j = k;
}
if (i != -1 && j != -1) {
ans = min(ans, abs(i - j));
}
}
return ans;
}
};Last updated