严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Shortest Word Distance IIDot5

Go down

Shortest Word Distance IIDot5 Empty Shortest Word Distance IIDot5

Post by Admin Sat Oct 21, 2017 6:00 pm

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

public int minDistance(String word1, String word2, String word3) {
if (!wordIndex.containsKey(word1) || !wordIndex.containsKey(word2) || !wordIndex.containsKey(word3))
return -1;

List<Integer> indexList1 = wordIndex.get(word1);
List<Integer> indexList2 = wordIndex.get(word2);
List<Integer> indexList3 = wordIndex.get(word3);
int index1 = 0;
int index2 = 0;
int index3 = 0;
int minDis = Integer.MAX_VALUE;
while (index1 < indexList1.size() && index2 < indexList2.size() && index3 < indexList3.size()) {
int val1 = indexList1.get(index1);
int val2 = indexList2.get(index2);
int val3 = indexList3.get(index3);
if (val1 < val2 && val1 < val3) {
int manhattan_dis = val2 - val1 + val3 - val1 + Math.abs(val2 - val3);
minDis = Math.min(manhattan_dis, minDis);
index1++;
}
else if (val2 < val1 && val2 < val3) {
int manhattan_dis = val3 - val2 + val1 - val2 + Math.abs(val1 - val3);
minDis = Math.min(manhattan_dis,minDis);
index2++;
}
else {
int totalDis = val1 - val3 + Math.abs(val2 - val1);
minDis = Math.min(minDis, totalDis);
index3++;
}
}
return minDis;
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum