[Leetcode] 243. Shortest Word Distance

这一题感觉里面放的是不是words都无所谓,是整型数也行,是啥都行。好像有过类似的题目但忘了
anyway,这题是easy的,很简单。就保持两个整型数作为两个单词的位置记录,数组里遇到对应的就更新对应的位置,一旦两个单词都出现过了就开始不停更新结果即可。没什么值得讲的,直接上代码吧。。
 

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

猜你喜欢

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