/* *244.Shortest Word Distance II *2016-6-18 by Mingyang *就是利用一个Map来存所有的数据,直接取就好了 */ class WordDistance { private Map<String, List<Integer>> map = new HashMap<String, List<Integer>>(); public WordDistance(String[] words) { for (int i = 0; i < words.length; i++) { String s = words[i]; List<Integer> list; if (map.containsKey(s)) { list = map.get(s); } else { list = new ArrayList<Integer>(); } //就算新加的数也不要忘了加到list里面 list.add(i); map.put(s, list); } } public int shortest(String word1, String word2) { List<Integer> l1 = map.get(word1); List<Integer> l2 = map.get(word2); int min = Integer.MAX_VALUE; //Java 5以后才有的循环表达,可int也可Integer for (int a : l1) { for (int b : l2) { min = Math.min(Math.abs(b - a), min); } } return min; } }