Sunday, October 7, 2018

245. Shortest Word Distance III




word1 ... word1 ... word1 ... word2
always update lastIndex no matter it is a pair or not


50.68 %
class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int lastIndex = -1;
        int min = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                if (lastIndex != -1 && words[lastIndex].equals(word2)) {
                    min = Math.min(min, i - lastIndex);
                }
                lastIndex = i;
            } else if (words[i].equals(word2)) {
                if (lastIndex != -1 && words[lastIndex].equals(word1)) {
                    min = Math.min(min, i - lastIndex);
                }
                lastIndex = i;
            }
        }
        return min;
    }
}

No comments:

Post a Comment