资讯专栏INFORMATION COLUMN

[LeetCode] 243. Shortest Word Distance

高胜山 / 1780人阅读

Problem

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

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

Solution
class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        if (word1.equals(word2)) return 0;
        int m = -1, n = -1;
        int min = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                m = i;
                if (n != -1) min = Math.min(min, m-n);
            } else if (words[i].equals(word2)) {
                n = i;
                if (m != -1) min = Math.min(min, n-m);
            }
        }
        if (m == -1 || n == -1) return -1;
        return min;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72709.html

相关文章

  • [Leetcode] Shortest Word Distance 最短单词间距

    摘要:代码第一次写入就先不比较第一次写入就先不比较哈希表法复杂度时间空间思路因为会多次调用,我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,就把每个单词的下标找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...

    jsliang 评论0 收藏0
  • [LeetCode] 244. Shortest Word Distance II

    Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...

    Nekron 评论0 收藏0
  • [LeetCode] 245. Shortest Word Distance III

    Problem Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. word1 and word2 may be the same and they represent two individual words i...

    csRyan 评论0 收藏0
  • [LeetCode] 126. Word Ladder II

    摘要:存放过程中的所有集合为所有的结尾,则顺序存放这个结尾对应的中的所有存放同一个循环的新加入的,在下一个循环再依次对其中元素进行进一步的把首个字符串放入新,再将放入,并将键值对放入,进行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...

    wayneli 评论0 收藏0
  • Leetcode PHP题解--D49 821. Shortest Distance to a Ch

    摘要:返回字符串中每一个字符离给定的字符的最短距离。否则,当当前下标大于上一个出现字符的位置,且存在下一个字符时,距离为两者中最小的那个。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D49 821. Shortest Distance to a Character 题目链接 821. Shortest Distance to a Character 题目分析 给定一个字符串s和一个字符...

    Shisui 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<