Shortest Word DistanceIII
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 数据结构的使用:使用HashMap:ShortestWordDistance系列(也有可能电话面试题)
Page 1 of 1
Shortest Word DistanceIII
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);
}
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);
}
Similar topics
» Shortest Word DistanceII
» Shortest Word Distance IIDot5
» Word Distance Finder
» Word LadderII Each Time Delete每次删除一个字符
» Word Search I leetcode 原题 amazon onsite特喜欢考
» Shortest Word Distance IIDot5
» Word Distance Finder
» Word LadderII Each Time Delete每次删除一个字符
» Word Search I leetcode 原题 amazon onsite特喜欢考
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 数据结构的使用:使用HashMap:ShortestWordDistance系列(也有可能电话面试题)
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|