Word Distance
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 list.
Example
Assume that words =["practice", "makes", "perfect", "coding", "makes"].
Input:
word1 = “coding”,
word2 = “practice”
Output: 3Input:
word1 = "makes",
word2 = "coding"
Output: 1Note 1
只call一次的normal情况
遍历一遍words list,找到word1就更新pointer1,找到word2就更新pointer2。 每找到任何一个word,就计算出当前distance,跟min打擂台。
时间复杂度:O(n) 空间复杂度:O(1)
Code1
Note 2
多次调用
会调用shortest函数非常多次,所以使用HashMap来存储words,key为word,value为index组成的list。 计算shortest word distance的时候,使用双指针遍历一遍即可。
时间复杂度 存储:O(N),查找:O(m+n)/O(N)
空间复杂度 存储:O(N),查找:O(N)
Code 2
Note 3
相同单词不同位置
标示一下是否是相同的单词,不是相同的就正常处理,相同就单独处理一下
当遍历单词与单词1相同时,如果是same的话,two就更新为one
Code 3
Last updated