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

Shortest Word DistanceII

Go down

Shortest Word DistanceII Empty Shortest Word DistanceII

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 static int shortest(String word1, String word2) {
if (!wordIndex.containsKey(word1) && !wordIndex.containsKey(word2))
return -1;

int dis = Integer.MAX_VALUE;
List<Integer> indexList1 = wordIndex.get(word1);
List<Integer> indexList2 = wordIndex.get(word2);
int index1 = 0;
int index2 = 0;
while (index1 < indexList1.size() && index2 < indexList2.size()) {
int val1 = indexList1.get(index1);
int val2 = indexList2.get(index2);
if (val1 > val2) {
dis = Math.min(dis, val1 - val2);
index2++;
}
else {
dis = Math.min(dis, val2 - val1);
index1++;
}
}
return dis;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words={"coding", "makes", "perfect", "coding", "makes"};
String word1="coding",word2="makes";
WordDistance(words);
int dis=shortest(word1,word2);
System.out.println(dis);

}

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