原题

给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。

示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]

输入: word1 = “coding”, word2 = “practice”
输出: 3
输入: word1 = "makes", word2 = "coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-word-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

遍历一遍,记住每个元素下标,并进行求最小值,注意用equals

代码

package leetcode.Algorithms;

public class Solution_243 {
    public static void main(String[] args) {
        String[] words = {"practice", "makes", "perfect", "coding", "makes"};
        System.out.println(shortestWordDistance(words, "coding", "practice"));
    }

    public static int shortestWordDistance(String[] wordsDict, String word1, String word2) {
        int index_word1 = -1;
        int index_word2 = -1;
        int length = wordsDict.length;
        for (int i = 0; i < wordsDict.length; i++) {
            if (wordsDict[i].equals(word1)) {
                index_word1 = i;
            } else if (wordsDict[i].equals(word2)) {
                index_word2 = i;
            }
            if (index_word1 != -1 && index_word2 != -1) {
                length = Math.min(length, Math.abs(index_word1 - index_word2));
            }
        }

        return length;
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐