Very Clear and Straightforward Java Solution


  • 0

    Consider two cases separately, when word1 equals to word2 and word1 is not equals to word2.
    This solutions is very easy to get and suitable to use in interviews

    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            int minDist = Integer.MAX_VALUE;
            int index1 = -1, index2 = -1;
            boolean hasFirst = false, hasSecond = false;
            for (int i = 0; i < words.length; i++) {
                if (word1.equals(word2)) {
                    if (words[i].equals(word1)) {
                        if (hasFirst == false) {
                            index1 = i;
                            hasFirst = true;
                        } else if (hasSecond == false) {
                            index2 = i;
                            hasSecond = true;
                            minDist = Math.min(minDist, index2 - index1);
                        } else {
                            index1 = index2;
                            index2 = i;
                            minDist = Math.min(minDist, index2 - index1);
                        }
                    }
                } else {
                    if (words[i].equals(word1)) {
                        index1 = i;
                        hasFirst = true;
                    } else if (words[i].equals(word2)) {
                        index2 = i;
                        hasSecond = true;
                    }
                    if (hasFirst && hasSecond) {
                        minDist = Math.min(minDist, Math.abs(index2 - index1));
                    }
                }
            }
            return minDist;
        }
    }
    

Log in to reply
 

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