Shortest Word Distance---LeetCode243
阿新 • • 發佈:2018-11-06
題目描述
/**
* Shortest Word Distance—LeetCode243
* Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
* 給定一個數組和兩個單詞word1,word2,返回兩者最近的距離,
* word1和word2不相同,但是都可能在陣列中出現多次
* For example,
* Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
* Given word1 = “coding”, word2 = “practice”, return 3.
* Given word1 = “makes”, word2 = “coding”, return 1.
*
*/
解法
遍歷一個數組,當遍歷到word1或者word2時,用w1,w2分別記錄記錄下位置,每次出最小的距離
public int shortestDistance(String[] words, String word1, String word2) {
int distance=words.length;
int w1=-1;
int w2=-1;
for(int i=0;i<words.length;i++){
if(words[i].equals(word1)){
w1=i;
}
if (words[i].equals(word2)) {
w2=i;
}
if(w1!=-1&&w2!=-1){
distance=Math.min(distance,Math.abs(w1-w2));
}
}
return distance;
}