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

Shortest Word DistanceIII

Go down

Shortest Word DistanceIII Empty Shortest Word DistanceIII

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

public static int shortestWordDistance3(String[] words, String word1, String word2) {
int index1 = -1;
int index2 = -1;
boolean isSame = word1.equals(word2);
int dis = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
if (isSame) {
index2 = index1; //last index
index1 = i;
}
else {
index1 = i;
}
}
else if (words[i].equals(word2)) {
index2 = i;
}
if (index1 != -1 && index2 != -1) {
dis = Math.min(dis, Math.abs(index1 - index2));
}
}
return dis;
}


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] words={"practice", "makes", "perfect", "coding", "makes"};
String word1="makes",word2="coding";
int dis=shortestWordDistance3(words,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