Skip to content

Commit 064d73a

Browse files
committed
word break solution
1 parent 050a6b2 commit 064d73a

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

word-break/hyer0705.ts

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class TNode {
2+
isEndOf: boolean;
3+
children: Map<string, TNode>;
4+
5+
constructor() {
6+
this.isEndOf = false;
7+
this.children = new Map<string, TNode>();
8+
}
9+
}
10+
11+
class Trie {
12+
root: TNode;
13+
14+
constructor() {
15+
this.root = new TNode();
16+
}
17+
18+
insert(word: string): void {
19+
let currentNode = this.root;
20+
21+
for (const ch of word) {
22+
if (!currentNode.children.has(ch)) {
23+
currentNode.children.set(ch, new TNode());
24+
}
25+
26+
currentNode = currentNode.children.get(ch)!;
27+
}
28+
29+
currentNode.isEndOf = true;
30+
}
31+
32+
search(word: string): boolean {
33+
let currentNode = this.root;
34+
35+
for (const ch of word) {
36+
if (!currentNode.children.has(ch)) {
37+
return false;
38+
}
39+
40+
currentNode = currentNode.children.get(ch)!;
41+
}
42+
43+
return currentNode.isEndOf;
44+
}
45+
}
46+
47+
function wordBreak(s: string, wordDict: string[]): boolean {
48+
const sLen = s.length;
49+
50+
const dp: boolean[] = new Array(sLen + 1).fill(false);
51+
dp[0] = true;
52+
53+
const trie = new Trie();
54+
55+
for (const word of wordDict) {
56+
trie.insert(word);
57+
}
58+
59+
for (let i = 1; i <= sLen; i++) {
60+
for (let j = 0; j < i; j++) {
61+
if (dp[j]) {
62+
if (trie.search(s.substring(j, i))) {
63+
dp[i] = true;
64+
break;
65+
}
66+
}
67+
}
68+
}
69+
70+
return dp[sLen];
71+
}

0 commit comments

Comments
 (0)