LeetCode 244. Shortest Word Distance II

This is a repeat of the shortest word distance question.

#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <climits>
using namespace std;

/*
  This is a follow up to Shortest Word Distance. The only difference is now you are given a list of words
  and your method will be called repeatly many times with different parameters. How would you optimize it?
  For example
  Assume that words = ["practice", "makes", "perfect", "coding", "makes"];
  Given word1 = "coding", word2 = "practice", return 3.
  Given word1 = "makes", word2 = "coding", return 1.
*/

// I didn't follow the class statement. It should seperate the hashmap insertion from caculate distance.
// since this methods will called many times. HashMap is useful then.
int shorestDistance(vector<string>& words, string word1, string word2) {
  unordered_multimap<string, int> wordToIndex;
  int minDistance = INT_MAX;
  for(int i = 0; i < words.size(); ++i) {
    wordToIndex.insert({words[i], i});
    auto iter_1 = wordToIndex.find(word1);
    auto iter_2 = wordToIndex.find(word2);
    if(iter_1 != wordToIndex.end() && iter_2 != wordToIndex.end()) {
      minDistance = min(minDistance, abs(iter_1->second - iter_2->second));
    }
  }
  return minDistance;
}

int main(void) {
  vector<string> words{"practice", "makes", "perfect", "coding", "makes"};
  int dis = shorestDistance(words, "makes", "coding");
  cout << dis << endl;
}


你可能感兴趣的:(LeetCode 244. Shortest Word Distance II)