This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

243. Shortest Word Distance 的拓展,不同的是这次需要多次调用求最短单词距离的函数。

Python:

# Time:  init: O(n), lookup: O(a + b), a, b is occurences of word1, word2
# Space: O(n)
import collections class WordDistance:
# initialize your data structure here.
# @param {string[]} words
def __init__(self, words):
self.wordIndex = collections.defaultdict(list)
for i in xrange(len(words)):
self.wordIndex[words[i]].append(i) # @param {string} word1
# @param {string} word2
# @return {integer}
# Adds a word into the data structure.
def shortest(self, word1, word2):
indexes1 = self.wordIndex[word1]
indexes2 = self.wordIndex[word2] i, j, dist = 0, 0, float("inf")
while i < len(indexes1) and j < len(indexes2):
dist = min(dist, abs(indexes1[i] - indexes2[j]))
if indexes1[i] < indexes2[j]:
i += 1
else:
j += 1 return dist  

C++:

class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
} int shortest(string word1, string word2) {
int res = INT_MAX;
for (int i = 0; i < m[word1].size(); ++i) {
for (int j = 0; j < m[word2].size(); ++j) {
res = min(res, abs(m[word1][i] - m[word2][j]));
}
}
return res;
} private:
unordered_map<string, vector<int> > m;
};

C++:

class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
m[words[i]].push_back(i);
}
} int shortest(string word1, string word2) {
int i = 0, j = 0, res = INT_MAX;
while (i < m[word1].size() && j < m[word2].size()) {
res = min(res, abs(m[word1][i] - m[word2][j]));
m[word1][i] < m[word2][j] ? ++i : ++j;
}
return res;
} private:
unordered_map<string, vector<int> > m;
};

  

 

类似题目:

[LeetCode] 243. Shortest Word Distance 最短单词距离

[LeetCode] 245. Shortest Word Distance III 最短单词距离 III

All LeetCode Questions List 题目汇总

[LeetCode] 244. Shortest Word Distance II 最短单词距离 II的更多相关文章

  1. [LeetCode] 245. Shortest Word Distance III 最短单词距离 III

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

  2. LeetCode 243. Shortest Word Distance (最短单词距离)$

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  3. [LeetCode] Shortest Word Distance III 最短单词距离之三

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

  4. [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)

    Design a class which receives a list of words in the constructor, and implements a method that takes ...

  5. [LeetCode#244] Shortest Word Distance II

    Problem: This is a follow up of Shortest Word Distance. The only difference is now you are given the ...

  6. [LeetCode] 243. Shortest Word Distance 最短单词距离

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  7. [LeetCode] Shortest Word Distance II 最短单词距离之二

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  8. [Swift]LeetCode244.最短单词距离 II $ Shortest Word Distance II

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  9. LeetCode 245. Shortest Word Distance III (最短单词距离之三) $

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

随机推荐

  1. SQL进阶系列之11让SQL飞起来

    写在前面 SQL的性能优化是数据库使用者必须面对的重要问题,本节侧重SQL写法上的优化,SQL的性能同时还受到具体数据库的功能特点影响,这些不在本节讨论范围之内 使用高效的查询 参数是子查询时,使用E ...

  2. python dijkstra 最短路算法示意代码

    def dijkstra(graph, from_node, to_node): q, seen = [(0, from_node, [])], set() while q: cost, node, ...

  3. Kotlin中Range与异常体系剖析

    好用的集合扩展方法: 下面来看一下对于集合中好用的一些扩展方法,直接上代码: 如果我们想取出集合中的第一个值和最后一个值,用Java方式是get(0)和get(size-1),但是在Kotlin中提供 ...

  4. linux下写tomcat启动,重启的脚本

    启动: #bash/bin cd /finance/ LANG="en_US.UTF-8" export LANG /finance/tomcat8-finance/bin/cat ...

  5. axio 请求中参数是数组

    前言 最近在做 Vue 项目中,Get 请求中有的参数是数组,传 JSON 字符串是没有问题的,但是直接传数组就一直报错,有问题. 参数后面无故加了 [],例如:UserIds 变成 UserIds[ ...

  6. javax validation--参数基础校验

    Bean Validation 1.1当前实现是hibernate validator 5,且spring4才支持.接下来我们从以下几个方法讲解Bean Validation 1.1,当然不一定是新特 ...

  7. (生鲜项目)05. RESTful api, 和 VUE

    第一步: 什么是 RESTful api 总结: 使用http协议作为介质, 达到客户端修改服务器端资源的目的, 服务器只需要提供指定的api接口, 客户端根据http协议中的post/get/put ...

  8. jsp解决大文件断点续传

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

  9. H5页面中判断是安卓手机还是ios手机的方法;APP页面中嵌套的H5跳转到APP其他页面的方法。

    (一).在H5页面中,可以直接利用如下的方法来进行判断是安卓还是ios. var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linu ...

  10. UOJ46. 【清华集训2014】玄学 [线段树,二进制分组]

    UOJ 思路 模拟赛出了这题,结果我没学过二进制分组--一波主席树然后空间就爆炸了-- 用线段树维护时间序列,每个节点维护\(a_i\to x_i\times a_i+b_i,i\in [1,n]\) ...