Skip to content

Commit f7c50eb

Browse files
committed
numMatchingSubseq
1 parent 40c4709 commit f7c50eb

File tree

2 files changed

+55
-34
lines changed

2 files changed

+55
-34
lines changed
Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,34 @@
1-
import { counter } from "../substring-with-concatenation-of-all-words/counter.ts";
2-
3-
function numMatchingSubseq(s: string, words: string[]): number {
4-
const cnt = counter(words);
5-
const arr = Array(26)
6-
.fill(0)
7-
.map(() => new Set<[string, number]>());
8-
9-
for (const [w, count] of cnt) {
10-
arr[w.charCodeAt(0) - "a".charCodeAt(0)].add([w, count]);
11-
}
12-
let res = 0;
13-
for (const c of s) {
14-
const temp = arr[c.charCodeAt(0) - "a".charCodeAt(0)];
15-
for (const wordcount of temp) {
16-
const [word, count1] = wordcount;
17-
if (word.length === 1) {
18-
res += count1;
19-
temp.delete(wordcount);
20-
} else {
21-
const w1 = word.slice(1);
22-
if (w1.charCodeAt(0) === word.charCodeAt(0)) {
23-
wordcount[0] = word.slice(1);
24-
} else {
25-
temp.delete(wordcount);
26-
arr[w1.charCodeAt(0) - "a".charCodeAt(0)].add([w1, count1]);
27-
}
28-
}
29-
}
30-
}
31-
32-
return res;
33-
}
34-
export default numMatchingSubseq;
1+
import { counter } from "../substring-with-concatenation-of-all-words/counter.ts";
2+
3+
function numMatchingSubseq(s: string, words: string[]): number {
4+
const cnt = counter(words);
5+
const arr = Array(26)
6+
.fill(0)
7+
.map(() => new Set<[string, number]>());
8+
9+
for (const [w, count] of cnt) {
10+
arr[w.charCodeAt(0) - "a".charCodeAt(0)].add([w, count]);
11+
}
12+
let res = 0;
13+
for (const c of s) {
14+
const temp = arr[c.charCodeAt(0) - "a".charCodeAt(0)];
15+
for (const wordcount of temp) {
16+
const [word, count1] = wordcount;
17+
if (word.length === 1) {
18+
res += count1;
19+
temp.delete(wordcount);
20+
} else {
21+
const w1 = word.slice(1);
22+
if (w1.charCodeAt(0) === word.charCodeAt(0)) {
23+
wordcount[0] = word.slice(1);
24+
} else {
25+
temp.delete(wordcount);
26+
arr[w1.charCodeAt(0) - "a".charCodeAt(0)].add([w1, count1]);
27+
}
28+
}
29+
}
30+
}
31+
32+
return res;
33+
}
34+
export default numMatchingSubseq;
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { counter } from "../substring-with-concatenation-of-all-words/counter.ts";
2+
3+
export default function numMatchingSubseq(s: string, words: string[]): number {
4+
const cnt = counter(words);
5+
let res = 0;
6+
for (const [w, count] of cnt) {
7+
if (isSubsequence(w, s)) res += count;
8+
}
9+
return res;
10+
}
11+
12+
function isSubsequence(w: string, s: string) {
13+
let index = -1;
14+
15+
for (const c of w) {
16+
index = s.indexOf(c, index + 1);
17+
if (index < 0) return false;
18+
}
19+
20+
return true;
21+
}

0 commit comments

Comments
 (0)