Simple 3ms java solution


  • 0
    C
    public int shortestWordDistance(String[] words, String word1, String word2) {
            int pos1 = -1, pos2 = -1, distance = Integer.MAX_VALUE, equalcount = 0;
            boolean equal = word1.equals(word2);
            for(int i=0;i<words.length;i++){
                if(equal){
                    if(words[i].equals(word1)){
                        if(equalcount % 2 == 0) pos1 = i;
                        else pos2 = i;
                        equalcount++;
                    }
                }else{
                    if(words[i].equals(word1)) pos1 = i;
                    if(words[i].equals(word2)) pos2 = i;
                }
                if(pos1 != -1 && pos2 != -1) distance = Math.min(distance, Math.abs(pos1-pos2));
            }
            return distance;
        }
    

Log in to reply
 

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