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

Solution:Map<String, List<Integer>>

Time Complexity: 初始化:O(N) shortest(): O(重复个数)
Space Complexity: O(N)

Solution Code:

public class WordDistance {

    private Map<String, List<Integer>> map;

    public WordDistance(String[] words) {
        map = new HashMap<String, List<Integer>>();
        for(int i = 0; i < words.length; i++) {
            String w = words[i];
            if(map.containsKey(w)) {
                map.get(w).add(i);
            } else {
                List<Integer> list = new ArrayList<Integer>();
                list.add(i);
                map.put(w, list);
            }
        }
    }

    public int shortest(String word1, String word2) {
        List<Integer> list1 = map.get(word1);
        List<Integer> list2 = map.get(word2);
        int ret = Integer.MAX_VALUE;
        for(int i = 0, j = 0; i < list1.size() && j < list2.size(); ) {
            int index1 = list1.get(i), index2 = list2.get(j);
            if(index1 < index2) {
                ret = Math.min(ret, index2 - index1);
                i++;
            } else {
                ret = Math.min(ret, index1 - index2);
                j++;
            }
        }
        return ret;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 有人问:“南京哪里有桂花?”南京人笑了:“南京哪里都是桂花。”初听的时候不甚在意,我知道梧桐很多很多。桂花?...
    七七行记阅读 355评论 0 1
  • 银行渠道卖保险这个水是很深的啊;这里制作一个简单的介绍;让大家知道如何的去辨别银行里卖的是理财产品,还是保险产品;...
    本慈阅读 371评论 0 2
  • 冬天,只要有太阳,就会特别繁忙。被子、铺盖、枕头、衣服、鞋,能晒的通通抱出来,铺在晾衣杆上,搭在凳子上,摊在地面上...
    彧忞君阅读 213评论 0 0
  • 大嘴机器人科技有限公司是一家深耕智能制造业多年的新三板上市公司(证券代码:832227),300余名工作人员在大嘴...
    乱七八遭遭阅读 401评论 0 1