博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Shortest Word Distance II
阅读量:4967 次
发布时间:2019-06-12

本文共 2415 字,大约阅读时间需要 8 分钟。

This is a follow up of . 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.

Solution:

Use HashMap to store the indexs of each word.

1 public class WordDistance { 2     Map
> wordMap; 3 4 public WordDistance(String[] words) { 5 wordMap = new HashMap
>(); 6 for (int i = 0; i < words.length; i++) { 7 String word = words[i]; 8 if (wordMap.containsKey(word)) { 9 wordMap.get(word).add(i);10 } else {11 List
list = new ArrayList
();12 list.add(i);13 wordMap.put(word, list);14 }15 }16 }17 18 public int shortest(String word1, String word2) {19 // Get two index lists20 List
indList1 = wordMap.get(word1);21 List
indList2 = wordMap.get(word2);22 int p1 = 0, p2 = 0;23 int minDis = Integer.MAX_VALUE;24 while (true) {25 if (indList1.get(p1) < indList2.get(p2)) {26 // Move p1.27 while (p1 < indList1.size() && indList1.get(p1) < indList2.get(p2)) {28 minDis = Math.min(minDis, Math.abs(indList1.get(p1) - indList2.get(p2)));29 p1++;30 }31 if (p1 >= indList1.size())32 break;33 } else {34 // Move p2.35 while (p2 < indList2.size() && indList2.get(p2) < indList1.get(p1)) {36 minDis = Math.min(minDis, Math.abs(indList1.get(p1) - indList2.get(p2)));37 p2++;38 }39 if (p2 >= indList2.size())40 break;41 }42 }43 return minDis;44 }45 }46 47 48 // Your WordDistance object will be instantiated and called as such:49 // WordDistance wordDistance = new WordDistance(words);50 // wordDistance.shortest("word1", "word2");51 // wordDistance.shortest("anotherWord1", "anotherWord2");

 

转载于:https://www.cnblogs.com/lishiblog/p/5798926.html

你可能感兴趣的文章
SqlCel 和MySQL for Excel在批量处理数据上的优劣
查看>>
leetcode【67】-Bulb Switcher
查看>>
JS验证图片格式和大小并预览
查看>>
调节心态的十种做法
查看>>
laravel5.2 移植到新服务器上除了“/”路由 ,其它路由对应的页面显示报404错误(Object not found!)———新装的LAMP没有加载Rewrite模块...
查看>>
潜罪犯
查看>>
编写高质量代码--改善python程序的建议(六)
查看>>
windows xp 中的administrator帐户不在用户登录内怎么解决?
查看>>
[spfa] Jzoj P4722 跳楼机
查看>>
代码审计入门后审计技巧
查看>>
Linux-Rsync服务器/客户端搭建实战
查看>>
接口和抽象类有什么区别
查看>>
简单通过百度api自动获取定位-前端实现
查看>>
180117 我的宠物识别判断语句
查看>>
JavaScript修炼之道pdf
查看>>
自己动手构造编译系统++编译、汇编与链接pdf
查看>>
JAVA 中文件读写函数BufferedReader 和 BufferedWriter 的使用
查看>>
Codeforces Round #206 (Div. 2)
查看>>
提升混合应用页面打开速度的新思路
查看>>
Mycat分表分库
查看>>