O(n) Intuitive Java


  • 0
    A
        public int shortestDistance(String[] words, String word1, String word2) {
            int j = 1; int min = Integer.MAX_VALUE;
            String find = null; String found = null;
            for(int i = 0; i < words.length; i++){
                while(i < words.length && !(words[i].equals(word1) || words[i].equals(word2))){
                    i++; j++;
                }
                if(i>=words.length) break;
                if(words[i].equals(find)) min = Math.min(min,j);
                find = words[i].equals(word1) ? word2 : word1;
                j = 1;
            }
            return min;
        }
    

Log in to reply
 

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