Java clean solution


  • 0
    R

    last_p1 and last_p2 to track last position of the p1 and p2. This variable will be used when word1 and word2 will be similar

    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            int p1 = -1, p2 = -1, last_p1 = -1,last_p2 = -1,min = Integer.MAX_VALUE;
            
            for (int i = 0; i < words.length; i++) {
                if (words[i].equals(word1)){
                    last_p1 = p1;
                    p1 = i;
                }
                    
        
                if (words[i].equals(word2)) {
                    last_p2 = p2; 
                	p2 = i;
                  
                }
                    
                if (p1 != -1 && p2 != -1){
                    if(word1.equals(word2)){
                        if (last_p1 != -1 && last_p2 != -1)
                            min = Math.min(min, Math.min(Math.abs(p2-last_p1), Math.abs(p1-last_p2)));
                    }else{
                        min = Math.min(min, Math.abs(p1 - p2));
                    }
                }
                    
            }
            
            return min;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.