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

Word Distance Finder

Go down

Word Distance Finder Empty Word Distance Finder

Post by Admin Sat Oct 21, 2017 5:59 pm

Map<String, List<Integer>> wordIndex = new HashMap<>();
public WordDistanceFinder (List<String> words) {
for (int i = 0; i < words.size(); i++) {
String curr = words.get(i);
if (!wordIndex.containsKey(curr))
wordIndex.put(curr, new ArrayList<Integer>());
wordIndex.get(curr).add(i);
}
}
public int distance (String wordOne, String wordTwo) {
if (wordOne.equals(wordTwo))
return 0;
List<Integer> indexList1 = wordIndex.get(wordOne);
List<Integer> indexList2 = wordIndex.get(wordTwo);
int index1 = 0, index2 = 0, min = Integer.MAX_VALUE;
while (index1 < indexList1.size() && index2 < indexList2.size()) {
int val1 = indexList1.get(index1), val2 = indexList2.get(index2);
if (val1 < val2) {
min = Math.min(min, val2 - val1);
index1++;
} else {
min = Math.min(min, val1 - val2);
index2++;
}
}
return min;
}


public static void main(String[] args) {
WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
System.out.println(finder.distance("fox", "quick") == 1);
System.out.println(finder.distance("quick", "brown") == 1);
}

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