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.
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
摘要:代码第一次写入就先不比较第一次写入就先不比较哈希表法复杂度时间空间思路因为会多次调用,我们不能每次调用的时候再把这两个单词的下标找出来。我们可以用一个哈希表,在传入字符串数组时,就把每个单词的下标找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...
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...
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...
摘要:存放过程中的所有集合为所有的结尾,则顺序存放这个结尾对应的中的所有存放同一个循环的新加入的,在下一个循环再依次对其中元素进行进一步的把首个字符串放入新,再将放入,并将键值对放入,进行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...
摘要:返回字符串中每一个字符离给定的字符的最短距离。否则,当当前下标大于上一个出现字符的位置,且存在下一个字符时,距离为两者中最小的那个。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D49 821. Shortest Distance to a Character 题目链接 821. Shortest Distance to a Character 题目分析 给定一个字符串s和一个字符...
阅读 2939·2021-11-25 09:43
阅读 3543·2021-11-24 11:13
阅读 3339·2021-10-14 09:42
阅读 2502·2021-09-23 11:53
阅读 3581·2021-09-22 15:57
阅读 3197·2021-09-02 09:54
阅读 3478·2019-08-30 13:47
阅读 1623·2019-08-29 16:55