原题链接在这里:https://leetcode.com/problems/shortest-word-distance-ii/

题目:

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.

题解:

method 会被call好多次,没有必要每次都traverse 一遍words array. 简历一个HashMap, key是word, value是该word出现index的list.

双指针遍历word1 和 word2 两个index list 计算最小距离.

Time Complexity: Constructor WordDistance O(words.length). shortest O(list1.size()+list2.size()).

Space: O(words.length).

AC Java:

 public class WordDistance {

     HashMap<String, List<Integer>> hm;
public WordDistance(String[] words) {
hm = new HashMap<String, List<Integer>>();
for(int i = 0; i<words.length; i++){
if(!hm.containsKey(words[i])){
List<Integer> ls = new ArrayList<Integer>();
hm.put(words[i], ls);
}
hm.get(words[i]).add(i);
}
} public int shortest(String word1, String word2) {
List<Integer> l1 = hm.get(word1);
List<Integer> l2 = hm.get(word2);
int res = Integer.MAX_VALUE;
int i = 0;
int j = 0;
while(i<l1.size() && j<l2.size()){
int index1 = l1.get(i);
int index2 = l2.get(j);
if(index1<index2){
res = Math.min(res, index2-index1);
i++;
}else{
res = Math.min(res, index1-index2);
j++;
}
}
return res;
}
} // Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");

类似Shortest Word Distance.

跟上Shortest Word Distance III.

最新文章

  1. 8.adr与ldr伪指令的区别
  2. 3.1 SharePreference
  3. DLUTOJ 1331 Maximum Sum
  4. C++中虚函数的作用浅析
  5. ManualResetEvent和AutoResetEvent的区别实例
  6. 构建高性能服务(三)Java高性能缓冲设计 vs Disruptor vs LinkedBlockingQueue--转载
  7. node.js模块之util模块
  8. HDU 1207
  9. eclipse kepler 创建 maven web 项目
  10. 在asp.net页面上按回车会触发Imagebutton控件的Click事件
  11. Struts2实现文件下载
  12. Struts2--验证框架
  13. Python基础【第一篇】
  14. Doing Homework HDU - 1074 (状压dp)
  15. 安装使用Entity Framework Power Tool Bate4 (Code First)从已建好的数据自动生成项目中的对应Model(新手贴,望各位大侠给予指点)
  16. Android中pm命令用法(转)
  17. 理解JavaScript模仿块作用域
  18. [Done]BTrace使用小记
  19. [Elixir002]节点启动后自动连接其它节点
  20. [PAT] 1144 The Missing Number(20 分)

热门文章

  1. CentOS 安装Gitolite 服务器
  2. ckeditor的详细配置
  3. 对socket的一点理解笔记
  4. 连接access的语句
  5. 【转】【Asp.Net MVC】asp.net mvc Model验证总结及常用正则表达式
  6. 对Get-Content参数-readcount的解释
  7. 单词游戏-基于SQLite+Qt的C++项目
  8. ZOJ 2974 矩阵快速幂
  9. DS实验题 Searchname
  10. 微信的User-Agent