Clean JAVA Solution


  • 0
    A
     public int shortestDistance(String[] words, String word1, String word2) {
        int index1 = words.length;
        int index2 = -1 * words.length;
        int min = Integer.MAX_VALUE;
        
        for(int i =0;i<words.length;i++) {
            if(words[i].equals(word1)) {
                index1 = i;
            } else if(words[i].equals(word2)) {
                index2 = i;
            }
            min = Math.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.