-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_153.js
More file actions
45 lines (40 loc) Β· 1.02 KB
/
problem_153.js
File metadata and controls
45 lines (40 loc) Β· 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Find smallest distance between two given words (brute force)
* @param {string} w1
* @param {string} w2
* @param {string} phrase
* @return {number}
*/
function smallestDistance(w1, w2, phrase) {
if (w1 === w2) return 'assuming words are different';
let tempHolder = [];
let minDist = Number.MAX_VALUE;
phrase.split(' ').forEach(word => {
if (word === w1) {
if (tempHolder.includes(w1)) {
tempHolder = [];
tempHolder.push(word);
} else {
tempHolder.push(word);
}
} else if (word === w2) {
minDist = Math.min(minDist, tempHolder.length - 1);
} else if (tempHolder.includes(w1)) {
tempHolder.push(word);
}
});
return minDist;
}
console.log(
smallestDistance(
'hello',
'world',
'dog cat hello cat dog dog hello cat world'
)
); // 1
console.log(
smallestDistance('hello', 'world', 'dog cat hello hello hello cat cat world')
); // 2
console.log(
smallestDistance('dog', 'cat', 'dog cat hello hello hello cat cat world')
); // 0