Skip to content

Commit 53e58a1

Browse files
committed
feat: Add solution for LeetCode problem 211
1 parent ab551a4 commit 53e58a1

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//
2+
// 211. Design Add and Search Words Data Structure
3+
// https://leetcode.com/problems/design-add-and-search-words-data-structure/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/28.
7+
//
8+
9+
private final class Node {
10+
var children: [Character: Node]
11+
var endOfWord: Bool
12+
13+
init(
14+
children: [Character: Node] = [:],
15+
endOfWord: Bool = false
16+
) {
17+
self.children = children
18+
self.endOfWord = endOfWord
19+
}
20+
}
21+
22+
final class WordDictionary {
23+
private let root: Node
24+
25+
init() {
26+
root = Node()
27+
}
28+
29+
func addWord(_ word: String) {
30+
var node = root
31+
for character in word {
32+
if node.children[character] == nil {
33+
node.children[character] = Node()
34+
}
35+
node = node.children[character]!
36+
}
37+
node.endOfWord = true
38+
}
39+
40+
func search(_ word: String) -> Bool {
41+
let word = Array(word)
42+
func dfs(index: Int, node: Node) -> Bool {
43+
guard index < word.count else { return node.endOfWord }
44+
45+
let character = word[index]
46+
if character == "." {
47+
return node.children.values.contains { dfs(index: index + 1, node: $0) }
48+
} else if let nextNode = node.children[character] {
49+
return dfs(index: index + 1, node: nextNode)
50+
}
51+
return false
52+
}
53+
return dfs(index: 0, node: root)
54+
}
55+
}

0 commit comments

Comments
 (0)