Simple java solution beating 75%


  • 0
    V
    public class WordDistance {
        HashMap<String, List<Integer>> map = new HashMap<>();
        public WordDistance(String[] words) {
            for(int i = 0; i < words.length; i++){
                if(map.containsKey(words[i])) map.get(words[i]).add(i);
                else{
                    List<Integer> l = new ArrayList<Integer>();
                    l.add(i);
                    map.put(words[i], l);
                }
            }
        }
    
        public int shortest(String word1, String word2) {
            List<Integer> w1 = map.get(word1);
            List<Integer> w2 = map.get(word2);
            int answer = Integer.MAX_VALUE;
            for(int i : w1){
                for(int j : w2){
                    answer = Math.min(answer, Math.abs(i - j));
                    if(i < j) break;
                }
            }
            return answer;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.