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. ACAG 0x02-8 非递归实现组合型枚举

    ACAG 0x02-8 非递归实现组合型枚举 之所以专门来写这道题的博客,是因为感觉从最根本处了解到了递归的机器实现. 主要的就是两个指令--Call和Ret. Call指令会将返回地址入栈(系统栈) ...

  2. gson之将对象转化成json字符串的方法

    public class GsonUtil { /** * 将object对象转成json格式字符串 */ public static String toJson(Object object) { G ...

  3. .NET 使用 VLC 播放视频

    使用 VLC 播放监控有几个月了,现在是多个项目中都有用到.在使用的过程中也有一些细节供大家参考. 一.对 VLC 的了解 VLC 是一个开源的跨平台多媒体播放器及框架. VLC 官方出的有播放器.编 ...

  4. Alpha冲刺(6/10)——2019.4.29

    所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(6/10)--2019.4.29 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...

  5. danci2

    composite 英 ['kɒmpəzɪt] 美 [kɑm'pɑzɪt] n. 复合材料:合成物:菊科 adj. 复合的:合成的:菊科的 vt. 使合成:使混合 a composite of 网络释 ...

  6. oracle连接出现的坑

    一.错误代码提示 请输入用户名:  SYS 输入口令: ERROR: ORA-28009: connection as SYS should be as SYSDBA or SYSOPER 二.解决方 ...

  7. lambda()函数

    lambda lambda原型为:lambda 参数:操作(参数) lambda函数也叫匿名函数,即没有具体名称的函数,它允许快速定义单行函数,可以用在任何需要函数的地方.这区别于def定义的函数. ...

  8. hdu4767 Bell——求第n项贝尔数

    题意 设第 $n$ 个Bell数为 $B_n$,求 $B_n \ mod  \ 95041567$.($1 \leq  n  \leq  2^{31}$) 分析 贝尔数的概念和性质,维基百科上有,这里 ...

  9. c++实用语法

    数组的快捷初始化 int inq[110] memset(inq, 0, sizeof(inq)); string到char数组的转换: string str ("Please split ...

  10. 【洛谷P5158】 【模板】多项式快速插值

    卡常严重,可有采用如下优化方案: 1.预处理单位根 2.少取几次模 3.复制数组时用 memcpy 4.进行多项式乘法项数少的时候直接暴力乘 5.进行多项式多点求值时如果项数小于500的话直接秦九昭展 ...