Skip to content

Commit

Permalink
Created 208-Implement-Trie
Browse files Browse the repository at this point in the history
  • Loading branch information
loczek committed Jul 8, 2022
1 parent bc700fc commit 5d178e5
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions typescript/208-Implement-Trie.ts
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

0 comments on commit 5d178e5

Please sign in to comment.