Leetcode: Shortest Word Distance II

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 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.

哈希表法

复杂度

时间 O(N) 空间 O(N)

思路

因为会多次调用,我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,使用HashMap来储存word以及word在Array里面出现的index。这样当调用最短距离的方法时,我们只要遍历两个单词的下标列表就行了。具体的比较方法,则类似merge two list,每次比较两个list最小的两个值,得到一个差值。然后把较小的那个给去掉。因为我们遍历输入数组时是从前往后的,所以下标列表也是有序的。

 1 public class WordDistance {
 2     
 3     HashMap<String, ArrayList<Integer>> map;
 4 
 5     public WordDistance(String[] words) {
 6         this.map = new HashMap<String, ArrayList<Integer>>();
 7         for (int i=0; i<words.length; i++) {
 8             String item = words[i];
 9             if (map.containsKey(item)) {
10                 map.get(item).add(i);
11             }
12             else {
13                 ArrayList<Integer> list = new ArrayList<Integer>();
14                 list.add(i);
15                 map.put(item, list);
16             }
17         }
18     }
19 
20     public int shortest(String word1, String word2) {
21         ArrayList<Integer> l1 = map.get(word1);
22         ArrayList<Integer> l2 = map.get(word2);
23         int minDis = Integer.MAX_VALUE;
24         int i=0, j=0;
25         while (i<l1.size() && j<l2.size()) {
26             int p1 = l1.get(i);
27             int p2 = l2.get(j);
28             minDis = Math.min(minDis, Math.abs(p1-p2));
29             if (p1 < p2) i++;
30             else j++;
31         }
32         return minDis;
33     }
34 }
35 
36 // Your WordDistance object will be instantiated and called as such:
37 // WordDistance wordDistance = new WordDistance(words);
38 // wordDistance.shortest("word1", "word2");
39 // wordDistance.shortest("anotherWord1", "anotherWord2");

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109200.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 栈与队列的区别_栈和队列

    栈与队列的区别_栈和队列1、队列先进先出,栈先进后出。2、对插入和删除操作的"限定"不同。栈是限定只能在表的一端进行插入和删除操作的线性表。   队列是限定只能在表的一端进行插入和在另一端进行删除操作的线性表。  3、遍历数据速度不同。栈只能从头部取数据,也就最先放入的需要遍历整个栈最后才能取出来,而且在遍历数据的时候还得为数据开辟临时空间,保持数据在遍历前的一致性。队列则不同,它基于地址指针…

    2025年7月11日
    2
  • PostMan使用教程。

    PostMan使用教程。原地址:https://blog.csdn.net/haibo0668/article/details/83828184 Postman教程——发送第一个请求 Postman教程——创建第一个集合 Postman教程——界面功能导航 Postman教程——设置 Pos…

    2022年5月7日
    41
  • SpringBoot跨域的几种解决方案

    SpringBoot跨域的几种解决方案SpringBoot跨域请求处理方式方法一、SpringBoot的注解@CrossOrigin(也支持SpringMVC)简单粗暴的方式,Controller层在需要跨域的类或者方法上加上该注解即可@RestController@CrossOrigin@RequestMapping(“/situation”)publicclassSituationControllerextendsPublicUtilController{@AutowiredprivateSit

    2022年6月16日
    30
  • lnk2019无法解析的外部符号_declspec_无法解析的外部符号lnk2001

    lnk2019无法解析的外部符号_declspec_无法解析的外部符号lnk2001VisualStudio2015编译中出现此问题:errorLNK2019:无法解析的外部符号__vsnprintf,该符号在函数xxxx中被引用解决方案:1、可能是由于某些头文件的函数或者未连接某些链接库所引起,故将头文件和链接库包含进去就OK。2、在项目工程属性中将MFC的使用变为“在共享DLL中使用MFC”3、编译时加入以下代码#include&amp;amp;amp;lt;Windows.h…

    2022年9月25日
    3
  • visual studio2015 密钥_visualstudio2013

    visual studio2015 密钥_visualstudio2013参考自:《visualstudio2012密钥》https://zhidao.baidu.com/question/555696036850635212.htmlvs2012密钥序列号(保证完美激活);YKCW6-BPFPF-BT8C9-7DCTH-QXGWCRBCXF-CVBGR-382MK-DFHJ4-C69G8YQ7PR-QTHDM-…

    2022年10月14日
    2
  • win10 禁止自动更新(修改注册表)

    win10 禁止自动更新(修改注册表)参考:https://blog.csdn.net/qq_40833810/article/details/89045074?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task第一步:按win+R,输入regedit,回车打开注册表编辑器,…

    2022年5月5日
    122

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号