JAVA Solution - probably not the best


  • 0
    A
    public int shortestDistance(String[] words, String word1, String word2) {
        int word1Index = -1;
        int word2Index = -1;
        int minDiff = words.length;
        
        for(int i = 0; i < words.length; i++) {
            if (words[i].equals(word2)) {
                word2Index = i;
            } else if (words[i].equals(word1)) {
                word1Index = 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.