clueless coding // TODO: be smarter

LeetCode Shortest Word Distance: CPP Solution



TL;DR Code Solution


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