Leetcode 245 Solution

This article provides solution to leetcode question 245 (shortest-word-distance-iii)

https://leetcode.com/problems/shortest-word-distance-iii

Solution

class Solution {
public:
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        int j = -1;
        int min_dist = INT_MAX;
        bool same = word1 == word2;
        int last_same_word = 0;

        for (int i = 0; i < words.size(); i++)
        {
            int same_word = 0;
            if (word1 == words[i])
                same_word = 1;
            else if (word2 == words[i])
                same_word = 2;

            if (same_word != 0)
            {
                if (j != -1 && (same || last_same_word != same_word))
                    min_dist = min(min_dist, i - j);

                j = i;
                last_same_word = same_word;
            }
        }

        return min_dist;
    }
};