Sunday, October 9, 2022

245. Shortest Word Distance III

 

Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

 

Example 1:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1

Example 2:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
Output: 3

 

Constraints:

  • 1 <= wordsDict.length <= 105
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.

 

 

class Solution {
public:
    int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) {
        if (wordsDict.size() == 0) {
            return 0;
        }
        unordered_map<string, vector<int>> mp;
        for (int i = 0; i < wordsDict.size(); i++) {
            mp[wordsDict[i]].push_back(i);
        }
        int ans = INT_MAX;
        if (word1 != word2) {
            int i = 0, j = 0;
            auto dist_vec1 = mp[word1];
            auto dist_vec2 = mp[word2];
            while (i < dist_vec1.size() && j < dist_vec2.size()) {
                ans = min(ans, abs(dist_vec1[i] - dist_vec2[j]));
                if (dist_vec1[i] <= dist_vec2[j]) {
                    i++;
                } else {
                    j++;
                }
            }
        } else {
            auto vec = mp[word1];
            if (vec.size() == 1) {
                return 0;
            }
            int i = 1;
            while (i < vec.size()) {
                ans = min(ans, vec[i] - vec[i - 1]);
                i++;
            }
        }
        return ans;
    }
};

No comments:

Post a Comment