Skip to content

Commit 6dd9002

Browse files
author
Christian Encarnacion
committed
Update ReadMe.md
1 parent 79555bb commit 6dd9002

File tree

1 file changed

+45
-5
lines changed

1 file changed

+45
-5
lines changed

Trie/ReadMe.md

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,51 @@ Let's walk through the algorithm:
7676
mark node as a valid key
7777
else
7878
mark node as valid key
79-
80-
81-
82-
83-
79+
```
80+
81+
And the corresponding swift code:
82+
83+
```swift
84+
func insert(w: String) -> (word: String, inserted: Bool) {
85+
86+
let word = w.lowercaseString
87+
var currentNode = self.root
88+
var length = word.characters.count
89+
90+
if self.contains(word) {
91+
return (w, false)
92+
}
93+
94+
var index = 0
95+
var c = Array(word.characters)[index]
96+
97+
while let child = currentNode.children[String(c)] {
98+
currentNode = child
99+
length -= 1
100+
index += 1
101+
102+
if(length == 0) {
103+
currentNode.isWord()
104+
wordList.append(w)
105+
wordCount += 1
106+
return (w, true)
107+
}
108+
109+
c = Array(word.characters)[index]
110+
}
111+
112+
let remainingChars = String(word.characters.suffix(length))
113+
for c in remainingChars.characters {
114+
currentNode.children[String(c)] = Node(c: String(c), p: currentNode)
115+
currentNode = currentNode.children[String(c)]!
116+
}
117+
118+
currentNode.isWord()
119+
wordList.append(w)
120+
wordCount += 1
121+
return (w, true)
122+
}
123+
84124
```
85125

86126

0 commit comments

Comments
 (0)