JAVA Solution - Probably not the best


  • 0
    A
     public int shortestWordDistance(String[] words, String word1, String word2) {
        int word1Index = -1;
        int word2Index = -1;
        int minDiff = words.length;
        int turn = 0;
        
        for(int i = 0; i < words.length; i++) {
            if (words[i].equals(word2) && words[i].equals(word1)) {
                if (turn % 2 == 1) {
                    word2Index = i;
                } else {
                    word1Index = i;
                }
                turn++;
            } else {
                if (words[i].equals(word1)) {
                    word1Index = i;
                } else if (words[i].equals(word2)) {
                    word2Index = i;
                }
            }
            
            if (word2Index >= 0 && word1Index >= 0) {
                if (Math.abs(word2Index - word1Index) < minDiff) {
                    minDiff = Math.abs(word2Index - word1Index);
                }
            }
        }
        return minDiff;
    }

Log in to reply
 

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