Skip to content
Merged
Show file tree
Hide file tree
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
38 changes: 38 additions & 0 deletions design-add-and-search-words-data-structure/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class WordDictionary:

def __init__(self):
self.root = {"$": True}


# TC: O(W), SC: O(W)
def addWord(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node: # 글자가 node에 없으면
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

트라이를 사용하신 것 같은데 메서드 안에 직접 구현하신 부분이 읽을 때 깔끔하게 느껴졌습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@river20s 달레님 코드 해설을 보고 따라했습니다. 다시 한 번 복습도 해야겠네요 감사합니다!

node[ch] = {"$": False} # 아직 끝이 아님 표시
node = node[ch] # 자식 노드로 변경
node["$"] = True # 단어 끝 표시


# TC: O(26^W) => 최악의 경우 영어 알파벳 26개가 각 노드에서 다음 글자가 됨 * 글자수의 비례해서 호출 스택 깊어짐, SC: O(W)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

26은 변하지 않는 상수이기 때문에 여기서 TC를 O(W)로 봐도 무방하지 않을까 생각합니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@river20s 그럴 수 있겠네요! 최악의 경우 모든 알파벳의 경우가 나올 수 있다는 점을 기억하고 싶어 적었습니다 :)

def search(self, word: str) -> bool:
def dfs(node, idx):
if idx == len(word):
return node["$"]

ch = word[idx]
if ch in node:
return dfs(node[ch], idx + 1)
if ch == ".": # 글자가 .이라면
# 노드의 모든 자식 노드 호출 (어느 경로에서 글자가 일치할지 모르기 때문)
if any(dfs(node[k], idx + 1) for k in node if k != '$'):
return True
return False

return dfs(self.root, 0) # 최상위 노드, 최초 idx


# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
48 changes: 48 additions & 0 deletions design-add-and-search-words-data-structure/hi-rachel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class WordDictionary {
root: Record<string, any>;

constructor() {
this.root = { $: true };
}

addWord(word: string): void {
let node = this.root;
for (const ch of word) {
if (!(ch in node)) {
node[ch] = { $: false };
}
node = node[ch];
}
node["$"] = true;
}

search(word: string): boolean {
const dfs = (node: Record<string, any>, idx: number): boolean => {
if (idx === word.length) return node["$"];

const ch = word[idx];
if (ch === ".") {
for (const key in node) {
if (key !== "$" && dfs(node[key], idx + 1)) {
return true;
}
}
return false;
}

if (ch in node) {
return dfs(node[ch], idx + 1);
}

return false;
};
return dfs(this.root, 0);
}
}

/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/