AC Java Solution O(n)


  • 0
    K
    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            if(word1.equals(word2)) return minDistance(words, word1);
            int min = Integer.MAX_VALUE;
            int i=-1,j=-1,k=0;
            while(k < words.length) {
                if(words[k].equals(word1)) i=k;
                if(words[k].equals(word2)) j=k;
                if(i!=-1&&j!=-1) min = (min>Math.abs(i-j))?Math.abs(i-j):min;
                k++;
            }
            return min;
        }
    
        private int minDistance(String[] words, String word) {
            int k=-1,l=-1, min=Integer.MAX_VALUE;
            for(int i=0;i<words.length;i++) {
                if(words[i].equals(word)) {
                    if(k==-1) { k=i; continue; }
                    if(l==-1) { l=i; continue; }
                    min = Math.min(min, l-k);
                    k=l;
                    l=i;
                }
            }
            return Math.min(min, l-k);
        }
    }
    

Log in to reply
 

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