clueless coding // TODO: be smarter

LeetCode Shortest Word Distance III: CPP Solution



TL;DR Code Solution


int shortestWordDistance(vector<string>& words, string word1, string word2) {

    int result = INT_MAX;
    int index = -1;
    for (int i = 0; i < words.size(); i++) {
        if (words[i] == word1 || words[i] == word2) {
            if (index != -1 && (words[i] == word1 && words[index] == word2 || words[i] == word2 && words[index] == word1)) {
                result = min(result, i - index);
            }
            index = i;
        }
    }
    return result;

}