Shortest Word Distance
LC 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.
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int index1 = -1;
int index2 = -1;
int res = Integer.MAX_VALUE;
for(int i = 0; i < words.length; i++){
if(words[i].equals(word1)) index1 = i;
if(words[i].equals(word2)) index2 = i;
if(index1 != -1 && index2 != -1){
res = Math.min(res, Math.abs(index1 - index2));
}
}
return res;
}
}
lc 244
This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it?
public class WordDistance {
Map<String, List<Integer>> map;
public WordDistance(String[] words) {
map = new HashMap<String, List<Integer>>();
for(int i = 0; i < words.length; i++){
if(map.containsKey(words[i])){
map.get(words[i]).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(words[i], list);
}
}
}
public int shortest(String word1, String word2) {
List<Integer> arr1 = map.get(word1);
List<Integer> arr2 = map.get(word2);
int res = Integer.MAX_VALUE;
int i = 0, j = 0;
while(i < arr1.size() && j < arr2.size()){
if( arr1.get(i) < arr2.get(j) ){
res = Math.min(res, (arr2.get(j) - arr1.get(i)));
i++;
}else{
res = Math.min(res, (arr1.get(i) - arr2.get(j)));
j++;
}
}
return res;
}
}
lc 245
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = "makes", word2 = "makes", return 3.
这里注意当给第一个word赋值的时候,想着当word1 == word2的时候,就可以更新index2的值了
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int index1 = -1;
int index2 = -1;
int res = Integer.MAX_VALUE;
for(int i = 0; i < words.length; i++){
if(words[i].equals(word1)){
if(word1.equals(word2)){
index2 = index1;
}
index1 = i;
}else if(words[i].equals(word2)){
index2 = i;
}
if(index1 != -1 && index2 != -1){
res = Math.min(res, Math.abs(index1 - index2));
}
}
return res;
}
}