Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add 211-Design-Add-and-Search-Words-Data-Structure
  • Loading branch information
loczek authored Jul 6, 2022
commit 8c2b30ad222c06043ee8fa51890b9c847e21b039
55 changes: 55 additions & 0 deletions javascript/211-Design-Add-and-Search-Words-Data-Structure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class TrieNode {
constructor() {
this.children = {};
this.endOfWord = false;
}
}

class WordDictionary {
constructor() {
this.root = new TrieNode();
}

addWord(word) {
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) {
function dfs(j, root) {
let cur = root;

for (let i = j; i < word.length; i++) {
const c = word[i];

if (c === ".") {
for (const key in cur.children) {
if (Object.prototype.hasOwnProperty.call(cur.children, key)) {
const child = cur.children[key];

if (dfs(i + 1, child)) {
return true;
}
}
}
return false;
} else {
if (!(c in cur.children)) {
return false;
}
cur = cur.children[c];
}
}

return cur.endOfWord;
}
return dfs(0, this.root);
}
}