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);
     */
  • 相关阅读:
    UVA10740 Not the Best (K短路)
    UVA10967 The Great Escape(最短路)
    UVA 10841 Lift Hopping in the Real World(dijkstra)
    U盘启动的PE系统的制作方法
    让远程桌面支持多用户
    学习的书的下载地址
    刚安装完的vs2008写的ajax应用提示sys未定义
    AS3 Libs
    禁用触发器
    Microsoft .NET 类库开发的设计准则
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12190954.html
Copyright © 2011-2022 走看看