Skip to content

Commit 639d47d

Browse files
committed
Updated the trie implementation with isEmpty, count, and words properties.
1 parent dcf9d22 commit 639d47d

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Trie/Trie.playground/Contents.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ trie.contains(word: "a")
1313
trie.contains(word: "apple")
1414

1515
trie.insert(word: "apple")
16-
trie.contains(word: "apple")
16+
trie.contains(word: "apple")

Trie/Trie.playground/Sources/Trie.swift

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@
44
/// -wordCount (the number of words in the trie)
55
public final class Trie {
66
typealias Node = TrieNode<Character>
7+
8+
public fileprivate(set) var words: Set<String> = []
9+
10+
public var isEmpty: Bool {
11+
return count == 0
12+
}
13+
14+
public var count: Int {
15+
return words.count
16+
}
17+
718
fileprivate let root: Node
819

920
public init() {
@@ -14,7 +25,7 @@ public final class Trie {
1425
// MARK: - Basic Methods
1526
public extension Trie {
1627
func insert(word: String) {
17-
guard !word.isEmpty else { return }
28+
guard !word.isEmpty, !contains(word: word) else { return }
1829
var currentNode = root
1930

2031
var characters = Array(word.lowercased().characters)
@@ -34,6 +45,8 @@ public extension Trie {
3445
currentNode.isTerminating = true
3546
}
3647
}
48+
49+
words.insert(word)
3750
}
3851

3952
func contains(word: String) -> Bool {
@@ -56,7 +69,9 @@ public extension Trie {
5669
}
5770

5871
func remove(word: String) {
59-
guard !word.isEmpty else { return }
72+
guard !word.isEmpty, words.contains(word) else { return }
73+
words.remove(word)
74+
6075
var currentNode = root
6176

6277
var characters = Array(word.lowercased().characters)

0 commit comments

Comments
 (0)