Word Distance
Example
Input:
word1 = “coding”,
word2 = “practice”
Output: 3Input:
word1 = "makes",
word2 = "coding"
Output: 1Note 1
Code1
Note 2
Code 2
Note 3
Code 3
Last updated
Input:
word1 = “coding”,
word2 = “practice”
Output: 3Input:
word1 = "makes",
word2 = "coding"
Output: 1Last updated
public int shortestDistance1(String[] words, String word1, String word2) {
int one = -1, two = -1;
int res = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (word1.equals(words[i])) {
one = i;
}
if (word2.equals(words[i])) {
two = i;
}
if (one != -1 && two != -1) {
res = Math.min(res, Math.abs(one - two));
}
}
return res;
}HashMap<String, List<Integer>> map;
public WordDistance(String[] words) {
map = new HashMap();
for (int i = 0; i < words.length; i++) {
List<Integer> indexes = map.getOrDefault(words[i], new ArrayList());
indexes.add(i);
map.put(words[i], indexes);
}
}
public int shortest(String word1, String word2) {
List<Integer> p1 = map.get(word1);
List<Integer> p2 = map.get(word2);
int min = Integer.MAX_VALUE;
int i = 0, j = 0;
while (i < p1.size() && j < p2.size()) {
int wp1 = p1.get(i);
int wp2 = p2.get(j);
if (wp1 < wp2) {
min = Math.min(min, wp2 - wp1);
i++;
} else {
min = Math.min(min, wp1 - wp2);
j++;
}
}
return min;
}if (same) {
two = one; //former one
}public int shortestWordDistance(String[] words, String word1, String word2) {
boolean same = word1.equals(word2);
int one = -1, two = -1;
int res = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
if (same) {
two = one; //former one
}
one = i;
} else if (words[i].equals(word2)) {
two = i;
}
if (one != -1 && two != -1) {
res = Math.min(res, Math.abs(one - two));
}
}
return res;
}