LeetCode-Shortest Word Distance

LiBlog發表於2016-08-23

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 = ["practice", "makes", "perfect", "coding", "makes"].

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.

Solution:

two pointers, update word1 and word2's positions and the distance.

 1 public class Solution {
 2     public int shortestDistance(String[] words, String word1, String word2) {
 3         if (words.length<2) return -1;
 4     
 5         int p1 = -words.length, p2 = -words.length;
 6         int minDis = Integer.MAX_VALUE;
 7         for (int i=0;i<words.length;i++){
 8             if (!words[i].equals(word1) && !words[i].equals(word2)) continue;
 9 
10             if (words[i].equals(word1)){
11                 p1 = i;            
12             } else {
13                 p2 = i;
14             }
15             minDis = Math.min(minDis,Math.abs(p1-p2));
16         }
17         return minDis;
18         
19     }
20 }

 

相關文章