Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

244. Shortest Word Distance II #111

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

因为在一个数组里可能会有重复的元素,所以他的Key值是一组数据,是一个ArrayList public class WordDistance { Map<String,List> map = new HashMap<String, List>(); public WordDistance(String[] words) { for(int i = 0; i < words.length; i++) { List temp = map.get(words[i]); if(temp == null) { temp = new ArrayList(); } temp.add(i); map.put(words[i], temp); } }

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

}

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

Shawngbk commented 7 years ago

Linkedin