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.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Solution 1: simple iterate the array and keep track last different word appearance.
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int res=Integer.MAX_VALUE;
int n=words.length;
int pre1=-1, pre2=-1;
for (int i=0; i<n; i++) {
if (words[i].equals(word1)) pre1=i;
else if (words[i].equals(word2)) pre2=i;
else continue;
if (pre1>0 && pre2>0) res=Math.min(res,Math.abs(pre1-pre2));
}
return res;
}
}
没有评论:
发表评论