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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值