Short java AC solution


  • 0
    J
        public int shortestDistance(String[] words, String word1, String word2) {
            int n = words.length, min = n - 1;
            for(int i = 0, j = -1; i < n; i++){
                if(words[i].equals(word1) || words[i].equals(word2)){
                    if(j != -1 && !words[j].equals(words[i])) min = Math.min(min, i - j);
                    j = i;
                }
            }
            return min;
        }
    

    I used one index to store the previous word1 or word2 index.


Log in to reply
 

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