forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
class TrieNode { | ||
children: {}; | ||
endOfWord: boolean; | ||
constructor() { | ||
this.children = {}; | ||
this.endOfWord = false; | ||
} | ||
} | ||
|
||
class Trie { | ||
root: TrieNode; | ||
constructor() { | ||
this.root = new TrieNode(); | ||
} | ||
|
||
insert(word: string): void { | ||
let cur = this.root; | ||
|
||
for (const c of word) { | ||
if (!(c in cur.children)) { | ||
cur.children[c] = new TrieNode(); | ||
} | ||
cur = cur.children[c]; | ||
} | ||
cur.endOfWord = true; | ||
} | ||
|
||
search(word: string): boolean { | ||
let cur = this.root; | ||
|
||
for (const c of word) { | ||
if (!(c in cur.children)) { | ||
return false; | ||
} | ||
cur = cur.children[c]; | ||
} | ||
|
||
return cur.endOfWord; | ||
} | ||
|
||
startsWith(prefix: string): boolean { | ||
let cur = this.root; | ||
|
||
for (const c of prefix) { | ||
if (!(c in cur.children)) { | ||
return false; | ||
} | ||
cur = cur.children[c]; | ||
} | ||
|
||
return true; | ||
} | ||
} | ||
|
||
const trie = new Trie(); | ||
trie.insert("apple"); | ||
trie.search("apple"); // return True | ||
trie.search("app"); // return False | ||
trie.startsWith("app"); // return True | ||
trie.insert("app"); | ||
trie.search("app"); // return True |