zoukankan      html  css  js  c++  java
  • [LC] 244. Shortest Word Distance II

    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. Your method will be called repeatedly many times with different parameters. 

    Example:
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Input: word1 = “coding”, word2 = “practice”
    Output: 3
    
    Input: word1 = "makes", word2 = "coding"
    Output: 1

    class WordDistance {
        private Map<String, List<Integer>> mymap;
        public WordDistance(String[] words) {
            mymap = new HashMap<>();
            for (int i = 0; i < words.length; i++) {
                if (mymap.containsKey(words[i])) {
                    mymap.get(words[i]).add(i);
                } else {
                    List lst = new ArrayList<>();
                    lst.add(i);
                    mymap.put(words[i], lst);
                }
            }
        }
        
        public int shortest(String word1, String word2) {
            List<Integer> lst1 = mymap.get(word1);
            List<Integer> lst2 = mymap.get(word2);
            int i = 0, j = 0, res = Integer.MAX_VALUE;
            while (i < lst1.size() && j < lst2.size()) {
                res = Math.min(res, Math.abs(lst1.get(i) - lst2.get(j)));
                if (lst1.get(i) < lst2.get(j)) {
                    i += 1;
                } else {
                    j += 1;
                }
            }
            return res;
        }
    }
    
    /**
     * Your WordDistance object will be instantiated and called as such:
     * WordDistance obj = new WordDistance(words);
     * int param_1 = obj.shortest(word1,word2);
     */
  • 相关阅读:
    如何使用API创建OpenStack虚拟机?
    Windows Server 2012 新特性:IPAM的配置
    DNSSec
    Win Server 8中的利器:微软在线备份服务
    AD RMS总结
    开发中辅助功能
    开发中坑爹的地方
    Js 中常用方法
    asp.net 错误处理
    js中的注意事项(持续整理)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12190954.html
Copyright © 2011-2022 走看看