clueless coding // TODO: be smarter

LeetCode Shortest Word Distance: Java Solution



TL;DR Code Solution


public int shortestDistance(String[] words, String word1, String word2) {

    int result = Integer.MAX_VALUE;
    int index = -1;
    for (int i = 0; i < words.length; i++) {
        if (words[i].equals(word1) || words[i].equals(word2)) {
            if (index >= 0 && !words[i].equals(words[index])) {
                result = Math.min(i - index, result);
            }
            index = i;
        }
    }
    return result;

}