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)

    《哈佛大学公开课:幸福课》 学习笔记(1)视频链接:http://v.163.com/special/sp/positivepsychology.html当初《幸福课》在网易公开课很火,当然现在也很火。但是由于对门户热门内容的成见,再加上一个江湖骗子式的课程名字,我还以为是又一个简单空洞的心灵鸡汤。但是今天看完了第一节课,事实告诉我,真是要相信群众的眼睛呀,而且随便怀疑哈佛出品也未免太过自信。70+分钟的时间内,没有多少废话,反复

    2022年7月18日
    16
  • Oracle数据库ORA-12154: TNS: 无法解析指定的连接标识符解决方法[通俗易懂]

    Oracle数据库ORA-12154: TNS: 无法解析指定的连接标识符解决方法[通俗易懂]对于这个问题,对于我这种初学者来说是经常遇到的,今天就把可靠的解决发法记于此,希望能帮助到大家。ORA-12154:TNS:无法解析指定的连接标识符第一步:查看自己的Oracle服务是否打开。OracleDBConsoleORCL是Oracle网页端管理工具的服务,访问地址一般为“http://127.0.0.1:1158/em/console/logon/logon”,如果不习惯用…

    2022年7月19日
    18
  • 工厂模式 Factory Method[通俗易懂]

    工厂模式 Factory Method[通俗易懂]工厂模式 Factory Method动机模式定义实例结构图要点总结笔记动机在软件系统中,经常面临着创建对象的工作,由于需求的变换,需要创建的对象的具体类型经常变换。如何应对这种变换?如何绕过常规的对象创建方法(new),提供一种”封装机制“来避免客户程序和这种”具体对象创建工作“的紧耦合模式定义定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使得一个类的实例化延迟(目的:解耦,手段:虚函数)到子类实例朴素class ISplitter{public:

    2022年8月11日
    8
  • SQL Server数据仓库的基础架构规划

    SQL Server数据仓库的基础架构规划

    2021年11月27日
    38
  • ASP NET MVC OutputCache

    ASP NET MVC OutputCacheASP.NETMVC提供了一个Filter来实现缓存,如果这个Attribute在方法上,当前方法的输出会被缓存起来,如果Attribute在Controller上,控制器中所有的方法的输出都会被缓存起来。这里的缓存可以设置过期时间,并且可以设置输出策略等等。1.OutputCache简单Demo[OutputCache(Duration=60)]publicActionRe

    2022年7月23日
    13
  • 使用arpspoof进行ARP欺骗[通俗易懂]

    使用arpspoof进行ARP欺骗[通俗易懂]使用arpspoof进行ARP欺骗使用虚拟机上的kail进行测试基本原理我们将运行实际的ARP中毒攻击,重定向数据包流并使其流经我们的设备基本命令arpspooef-i网卡-t目标ip默认网关测试下面是我作为被攻击的kail,ip为192.168.25.129下面是我作为攻击的kail,网卡对应ip,网卡名字为eth0,ip为192.168.25.128使用上面…

    2022年10月7日
    4

发表回复

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

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