Shortest Word Distance III

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

Note: You may assume word1 and word2 are both in the list.

o(n)

class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        if(words == null || words.length == 0)
            return -1;
        
        //int p1 = -1, p2 = -1, res = Integer.MAX_VALUE;
        
//         for(int i = 0; i < words.length; i++){
//             //for word1 = word2 's condition to record word1's position
//             int t = p1;
                
//             if(words[i].equals(word1)) p1 = i;
//             if(words[i].equals(word2)) p2 = i;
            
//             if(p1 != -1 && p2 != -1){
//                 //这种情况 p1和p2都指在word2, t指在word1
//                 if(word1.equals(word2) && t!= -1 && t!=p1){
//                     res = Math.min(res,Math.abs(t-p1));
//                 }else{
//                     res = Math.min(res,Math.abs(p1-p2));
//                 }
//             }
//         }
        
//         return res == Integer.MAX_VALUE ? -1: res;
        
        int p1 = words.length, p2 = -words.length, res = Integer.MAX_VALUE;
        
        
        for(int i = 0; i < words.length;i++){
            if(words[i].equals(word1))
                p1 = word1.equals(word2) ? p2 : i;
            if(words[i].equals(word2))
                p2 = i;
            
            res = Math.min(res, Math.abs(p2 - p1));
        }
        
        return res;
    }
}

Last updated