Shortest Word Distance---LeetCode243

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangljanfxp/article/details/78493314

题目描述

/**
* Shortest Word Distance—LeetCode243
* Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
* 给定一个数组和两个单词word1,word2,返回两者最近的距离,
* word1和word2不相同,但是都可能在数组中出现多次
* For example,
* Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
* Given word1 = “coding”, word2 = “practice”, return 3.
* Given word1 = “makes”, word2 = “coding”, return 1.
*
*/

解法

遍历一个数组,当遍历到word1或者word2时,用w1,w2分别记录记录下位置,每次出最小的距离

public int shortestDistance(String[] words, String word1, String word2) {
        int distance=words.length;
        int w1=-1;
        int w2=-1;
        for(int i=0;i<words.length;i++){
            if(words[i].equals(word1)){
                w1=i;
            }
            if (words[i].equals(word2)) {
                w2=i;
            }
            if(w1!=-1&&w2!=-1){
                distance=Math.min(distance,Math.abs(w1-w2));
            }
        }
        return distance;
    }

猜你喜欢

转载自blog.csdn.net/yangljanfxp/article/details/78493314