This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?

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.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

思路:用hashmap存相同的word和index,然后读出两个word相应的index arraylist。从头开始比较index,方法是使两个index尽量接近,算出最小的distance。

 

public class WordDistance {
    Map<String,List<Integer>> res;

    public WordDistance(String[] words) {
        res=new HashMap<>();
       for(int i=0;i<words.length;i++)
       {
           if(!res.containsKey(words[i]))
           {
               res.put(words[i],new ArrayList<Integer>());
           }
               res.get(words[i]).add(i);
       }
        
    }

    public int shortest(String word1, String word2) {
    List<Integer> s1=res.get(word1);
    List<Integer> s2=res.get(word2);
    int i=0,j=0;
    int min=Integer.MAX_VALUE;
    while(i<s1.size()&&j<s2.size())
    {
        int index1=s1.get(i);
        int index2=s2.get(j);
        if(index1<index2)
        {
            min=Math.min(index2-index1,min);
            i++;
        }
        else
        {
            min=Math.min(index1-index2,min);
            j++;
        }
    }
    return min;
        
    }
}

// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");

 

posted on 2016-09-21 12:07  Machelsky  阅读(141)  评论(0)    收藏  举报