243-最短单词距离

最短单词距离

题目

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

给定一个单词列表和两个单词word1和word2,返回两个单词在列表中的最短距离.

例如

给定单词列表: ["practice", "makes", "perfect", "coding", "makes"].

给定单词

Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.

提示:你可以假设word1不等于word2,而且word1和word2都在列表中.

思路

遍历列表,然后依次比较单词,有相同的就开始计数

领扣要会员了...方法没有验证过

代码

class Solution {
    public int shortestDistance(List words, string word1, string word2) {
       if (words.size() < 2) {
            return -1;
        }
        int sum = -1;
        boolean flag = false;
        for (String word : words) {
            if (word.equals(word1) || word.equals(word2)) {
                sum = sum==-1?0:sum;
                flag = !flag;
            }
            if (flag) {
                sum++;
            }
        }
        return sum;
    }
}

你可能感兴趣的:(243-最短单词距离)