-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring-segmentation.js
51 lines (45 loc) · 1.28 KB
/
string-segmentation.js
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
46
47
48
49
50
51
//Brute force | O(n^2) | Loop counted 51
function stringSegmentation(arr, str) {
if (arr.length === 0 || str.length === 0) {
return [];
}
const components = {};
for (let i = 0; i < arr.length; i++) {
let to = 0;
let from = arr[i].length;
for (let j = 0; j < str.length; j++) {
if (str.slice(to, from) === arr[i] && !components[arr[i]]) {
components[arr[i]] = true
}
to++;
from++;
}
}
let segments = [];
for (const key in components) {
segments.push(key);
}
return segments;
}
//Optimized (Best) | O(n^2) | Loop counted 40
function stringSegmentation(arr, str) {
if (arr.length === 0 || str.length === 0) {
return [];
}
const components = new Set();
for (let i = 0; i < arr.length; i++) {
const wordLen = arr[i].length;
const strLen = str.length;
for (let j = 0; j <= strLen - wordLen; j++) {
if (arr[i] === str.slice(j, j + wordLen)) {
components.add(arr[i]);
}
}
}
return Array.from(components);
}
const arr = ['apple', 'apple', 'pear', 'pie'];
const str = 'applepearpie';
console.log(stringSegmentation(arr, str));
// OUTPUT
//[ 'apple', 'pear', 'pie' ]