243. Shortest Word Distance - cocoder39/coco39_LC GitHub Wiki

243. Shortest Word Distance

int shortestDistance(vector<string>& words, string word1, string word2) {
        int res = INT_MAX;
        int idx1 = -1, idx2 = -1;
        for (int i = 0; i < words.size(); i++) {
            if (words[i] == word1) {
                idx1 = i;
            }
            else if (words[i] == word2) {
                idx2 = i;
            }
            if (idx1 != -1 && idx2 != -1) {   
                res = min(res, abs(idx1 - idx2));
            }
        }
        return res;
    }
⚠️ **GitHub.com Fallback** ⚠️