My 1ms Java Solution


  • 0
    Y
    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            int index_1 = words.length;
            int index_2 = words.length;
            int min = Integer.MAX_VALUE;
            //corner case
            if(word1.equals(word2)){
                for(int i = 0; i < words.length; i++){
                    if(words[i].equals(word1)){
                        if(index_1 == words.length){
                            index_1 = i;
                        }
                        else{
                            min = Math.min(min,i-index_1);
                            index_1 = i;
                        }
                    }
                }
            }
            else{
                for(int i = 0; i < words.length; i++) {
                    if(words[i].equals(word1)){
                        index_1 = i;
                        min = Math.min(min,Math.abs(index_1-index_2));
                    }
                    else if(words[i].equals(word2)){
                        index_2 = i;
                        min = Math.min(min,Math.abs(index_1-index_2));
                    }
                }
            }
            return min;
        }
    }
    

Log in to reply
 

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