[Leetcode] 245. Shortest Word Distance III

Well. 这一题和Shortest Word Distance只有一个区别就是word1可以等于word2,此时要找的就是两个连续的最短的距离,而不是0。所以其实答案就是在Shortest Word Distance上面多加一个特别情况就是word1 = word2就可以了。直接上代码吧,没啥难的。

    public int shortestWordDistance(String[] words, String word1, String word2) {
        int idx1 = -1, idx2 = -1, result = Integer.MAX_VALUE;
        boolean sameWord = word1.equals(word2);
        for (int i = 0; i < words.length; i++) {
            if (sameWord && words[i].equals(word1)) {
                idx1 = idx2;
                idx2 = i;
            } else if (words[i].equals(word1)) {
                idx1 = i;
            } else if (words[i].equals(word2)) {
                idx2 = i;
            }
            
            if (idx1 != -1 && idx2 != -1) {
                result = Math.min(result, Math.abs(idx1 - idx2));
            }
        }
        
        return result;
    }

猜你喜欢

转载自blog.csdn.net/chaochen1407/article/details/81202841