您的位置:首页 > 其它

[LeetCode]Shortest Word Distance II

2015-11-28 09:33 267 查看
public class WordDistance {
private HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
List<Integer> list = map.containsKey(words[i]) ? map.get(words[i]) : new ArrayList<Integer>();
list.add(i);
map.put(words[i], list);
}
}

public int shortest(String word1, String word2) {
List<Integer> list1 = map.get(word1);
List<Integer> list2 = map.get(word2);
int result = Integer.MAX_VALUE;
int p1 = 0;
int p2 = 0;
int size1 = list1.size();
int size2 = list2.size();
while (p1 < size1 && p2 < size2) {
result = Math.min(result, Math.abs(list1.get(p1) - list2.get(p2)));
if (list1.get(p1) > list2.get(p2)) {
p2 ++;
} else {
p1 ++;
}
}
return result;
}
}

// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: