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);
     */
  • 相关阅读:
    3.2 Program Encodings 程序编码
    Describe your home
    Building vs solution in command line
    找到适合自己的人生轨迹 Angkor:
    每个月总有那么几天不想学习,不想写代码 Angkor:
    Linux下的Memcache安装
    敏捷开发之 12条敏捷原则
    为什么要用NIO
    memcached server LRU 深入分析
    Linux 脚本编写基础
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12190954.html
Copyright © 2011-2022 走看看