Java short sol


  • 0
    V
        Map<String, List<Integer>> hm;
        public WordDistance(String[] words) 
        {
            hm = new HashMap<String, List<Integer>>();
            for(int i = 0; i < words.length; i++)
            {
                List<Integer> temp = hm.getOrDefault(words[i], new ArrayList<Integer>());
                temp.add(i);
                hm.put(words[i], temp);
            }
        }
        
        public int shortest(String word1, String word2) 
        {
            int toRet = Integer.MAX_VALUE;
            List<Integer> t1 = hm.get(word1);
            List<Integer> t2 = hm.get(word2);
            int i = 0, j = 0, ii, jj;
            while(i < t1.size() && j < t2.size())
            {
                ii = t1.get(i);
                jj = t2.get(j);
                toRet = Math.min(toRet, (int)Math.abs(ii - jj));
                if(ii < jj)
                    i++;
                else
                    j++;
            }
            return toRet;
        }

Log in to reply
 

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