File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments