-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringMatchingInAnArray.ts
More file actions
41 lines (34 loc) · 1.21 KB
/
stringMatchingInAnArray.ts
File metadata and controls
41 lines (34 loc) · 1.21 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
// First Approach - Sorting words by their length to optimize search and comparing each word with next words with search method. (9ms - Beats 13.79%)
function stringMatching(words: string[]): string[] {
words.sort((a, b) => a.length - b.length);
let substringWords: string[] = [];
for(let i = 0; i < words.length; i++) {
for(let j = i + 1; j < words.length; j++) {
if(words[j].search(words[i]) !== -1) {
substringWords.push(words[i]);
break;
}
}
}
return substringWords;
};
// Second Approach - Identical to first approach but using indexOf method being more performatic. (1ms - Beats 93.10%)
function stringMatching(words: string[]): string[] {
words.sort((a, b) => a.length - b.length);
let substringWords: string[] = [];
for(let i = 0; i < words.length; i++) {
for(let j = i + 1; j < words.length; j++) {
if(words[j].search(words[i]) !== -1) {
substringWords.push(words[i]);
break;
}
}
}
return substringWords;
};
const case1 = stringMatching(["mass","as","hero","superhero"]);
const case2 = stringMatching(["leetcode","et","code"]);
const case3 = stringMatching(["blue","green","bu"]);
console.log(`case1: ${case1}`);
console.log(`case2: ${case2}`);
console.log(`case3: ${case3}`);