Java Using Hashmap,Not concise


  • 0
    W

    public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {

        int pos1 = -1;
        int pos2 = -1;
        int minDis = Integer.MAX_VALUE;
        Map<String,List<Integer>> mapping = new HashMap<String,List<Integer>>();
        
        for(int i = 0; i< words.length; i++){
            if(mapping.containsKey(words[i])){
                mapping.get(words[i]).add(i);
            }else{
                List<Integer> disList = new LinkedList<Integer>();
                disList.add(i);
                mapping.put(words[i],disList);
            }
        }//record the position
        
         if(word1.equals(word2)){
            List<Integer> list = mapping.get(word1);
            for(int i = 0; i< list.size() - 1 ; i++){
               minDis = Math.min(minDis,list.get(i+1)-list.get(i)); 
            }
        }else{
            List<Integer> list1 = mapping.get(word1);
            List<Integer> list2 = mapping.get(word2);
            for(int i = 0; i<list1.size(); i++){
                for(int j = 0; j<list2.size();j++){
                    minDis = Math.min(minDis, Math.abs(list1.get(i) - list2.get(j)));
                }
            }
        }
        return minDis;
        
    }
    

    }


Log in to reply
 

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