243. Shortest Word Distance
Problem:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
Assume that words =
["practice", "makes", "perfect", "coding", "makes"].
Given word1 =
Given word1 =
“coding”, word2 = “practice”, return 3.Given word1 =
"makes", word2 = "coding", return 1.
Analysis:
找到两个单词尽可能近的距离。比如2个单词位置顺序为
位置: 1,2,1,2,2
index: 0,2,4,5,7
肯定是0和2先比较。 走到4,word1又出现了一次,和2比较。走到5,word2出现第二次和4比较。
Solution:
class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0) return 0;
int idx = -1, min = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if(words[i].equals(word1) || words[i].equals(word2)) {
if (idx != -1 && words[i] != words[idx]) {
min = Math.min(i - idx, min);
}
idx = i;
}
}
return min;
}
}
评论
发表评论