3ms Accepted Simple Java Soln

  • 0
    public int shortestDistance(String[] words, String word1, String word2) {
            int N = words.length;
            int w1=N, w2=N, minDist=Integer.MAX_VALUE;
            for(int i=0; i<N; i++){
                    w1 = i;
                    minDist = Math.min(minDist, Math.abs(w1-w2));
                else if(word2.equals(words[i])){
                    w2 = i;
                    minDist = Math.min(minDist, Math.abs(w2-w1));
            return minDist;

Log in to reply

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