Skip to content

Commit 065574c

Browse files
committed
Finished all 3 Shortest Word Distance questions
1 parent 5d4fd7f commit 065574c

File tree

3 files changed

+113
-0
lines changed

3 files changed

+113
-0
lines changed

Easy/Shortest Word Distance II.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class WordDistance {
2+
3+
Map<String, List<Integer>> map;
4+
public WordDistance(String[] words) {
5+
map = new HashMap<>();
6+
7+
for (int i=0; i<words.length; i++) {
8+
if (map.containsKey(words[i])) {
9+
map.get(words[i]).add(i);
10+
}
11+
else {
12+
List<Integer> indexes = new ArrayList<>();
13+
indexes.add(i);
14+
15+
map.put(words[i], indexes);
16+
}
17+
}
18+
}
19+
20+
public int shortest(String word1, String word2) {
21+
List<Integer> index1 = map.get(word1);
22+
List<Integer> index2 = map.get(word2);
23+
24+
int i = 0;
25+
int j = 0;
26+
int diff = Integer.MAX_VALUE;
27+
28+
while (i < index1.size() && j < index2.size()) {
29+
diff = Math.min(diff, Math.abs(index1.get(i) - index2.get(j)));
30+
31+
if (index1.get(i) > index2.get(j)) {
32+
j++;
33+
}
34+
else {
35+
i++;
36+
}
37+
}
38+
39+
return diff;
40+
}
41+
}
42+
43+
/**
44+
* Your WordDistance object will be instantiated and called as such:
45+
* WordDistance obj = new WordDistance(words);
46+
* int param_1 = obj.shortest(word1,word2);
47+
*/

Easy/Shortest Word Distance III.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
public int shortestWordDistance(String[] words, String word1, String word2) {
3+
int dist1 = -1;
4+
int dist2 = -1;
5+
int minDist = Integer.MAX_VALUE;
6+
7+
boolean sameWord = word1.equals(word2);
8+
9+
for (int i=0; i<words.length; i++) {
10+
if (words[i].equals(word1)) {
11+
if (sameWord) {
12+
if (dist1 == -1) {
13+
dist1 = i;
14+
}
15+
}
16+
else {
17+
dist1 = i;
18+
}
19+
}
20+
21+
if (words[i].equals(word2)) {
22+
if (sameWord) {
23+
if (i != dist1) {
24+
dist2 = i;
25+
}
26+
}
27+
else {
28+
dist2 = i;
29+
}
30+
}
31+
32+
if (dist1 != -1 && dist2 != -1) {
33+
minDist = Math.min(minDist, Math.abs(dist1 - dist2));
34+
if (sameWord) {
35+
dist1 = dist2;
36+
dist2 = -1;
37+
}
38+
}
39+
}
40+
41+
return minDist;
42+
}
43+
}

Easy/Shortest Word Distance.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int shortestDistance(String[] words, String word1, String word2) {
3+
int dist1 = -1;
4+
int dist2 = -1;
5+
int minDist = Integer.MAX_VALUE;
6+
7+
for (int i=0; i<words.length; i++) {
8+
if (words[i].equals(word1)) {
9+
dist1 = i;
10+
}
11+
12+
if (words[i].equals(word2)) {
13+
dist2 = i;
14+
}
15+
16+
if (dist1 != -1 && dist2 != -1) {
17+
minDist = Math.min(minDist, Math.abs(dist1 - dist2));
18+
}
19+
}
20+
21+
return minDist;
22+
}
23+
}

0 commit comments

Comments
 (0)