AC Java solution


  • 0
    R
    public int shortestWordDistance(String[] words, String word1, String word2) {
            int index1 = -1;
            int index2 = -1;
            int min = Integer.MAX_VALUE;
            if(word1.equals(word2)){
                
                for(int i=0;i < words.length;i++){
                    if(words[i].equals(word1)){
                        if(index1 == -1){
                            index1 = i;
                        }else{
                            if(index2 == -1){
                                index2 = i;
                            }else{
                                index1 = index2;
                                index2 = i;
                            }
                        }
                        if(index1 != -1 && index2 != -1){
                            if(Math.abs(index1-index2) < min){
                                min = Math.abs(index1-index2);
                            }
                        }
                    }
                }
            }else{
                for(int i=0;i < words.length;i++){
                    if(words[i].equals(word1)){
                        index1 = i;
                    }else if(words[i].equals(word2)){
                        index2 = i;
                    }
                    
                    if(index1 != -1 && index2 != -1){
                        if(Math.abs(index1-index2) < min){
                                min = Math.abs(index1-index2);
                            }
                    }
                }
            }
            
            return min;
        }
    

Log in to reply
 

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