Java Simple Solution, O(n) time, O(1) space


  • 0
    D
    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            if (words.length == 0) return 0;
            
            boolean wordsAreTheSame = word1.equals(word2);
            
            int shortestDistance = Integer.MAX_VALUE;
            int word1Index = -1;
            int word2Index = -1;
            
            if (wordsAreTheSame) {
                boolean setFirst = true;
                for (int i = 0; i < words.length; i++) {
                    if (words[i].equals(word1)) {
                        if (setFirst) {
                            word1Index = i;
                            if (word2Index >= 0) shortestDistance = Math.min(shortestDistance, i - word2Index); 
                        } else {
                            word2Index = i;
                            if (word1Index >= 0) shortestDistance = Math.min(shortestDistance, i - word1Index);
                        }
                        setFirst = !setFirst;
                    }        
                }
            } else {
                for (int i = 0; i < words.length; i++) {
                    if (words[i].equals(word1)) {
                        word1Index = i;
                        if (word2Index >= 0) shortestDistance = Math.min(shortestDistance, i - word2Index);
                    }
                    if (words[i].equals(word2)) {
                        word2Index = i;
                        if (word1Index >= 0) shortestDistance = Math.min(shortestDistance, i - word1Index);
                    }
                }
            }
            
            return shortestDistance;
        }
    }
    

Log in to reply
 

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