Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
56 changes: 56 additions & 0 deletions lcof2/剑指 Offer II 062. 实现前缀树/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,62 @@ public class Trie {
*/
```

#### Swift

```swift
class Trie {
private var children: [Trie?]
private var isEnd: Bool

init() {
self.children = Array(repeating: nil, count: 26)
self.isEnd = false
}

func insert(_ word: String) {
var node = self
for char in word {
let index = Int(char.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
node.children[index] = Trie()
}
node = node.children[index]!
}
node.isEnd = true
}

func search(_ word: String) -> Bool {
if let node = searchPrefix(word) {
return node.isEnd
}
return false
}

func startsWith(_ prefix: String) -> Bool {
return searchPrefix(prefix) != nil
}

private func searchPrefix(_ prefix: String) -> Trie? {
var node = self
for char in prefix {
let index = Int(char.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
return nil
}
node = node.children[index]!
}
return node
}
}
/**
* Your Trie object will be instantiated and called as such:
* let trie = Trie()
* trie.insert(word);
* trie.search(word);
* trie.startsWith(prefix);
*/
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
51 changes: 51 additions & 0 deletions lcof2/剑指 Offer II 062. 实现前缀树/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Trie {
private var children: [Trie?]
private var isEnd: Bool

init() {
self.children = Array(repeating: nil, count: 26)
self.isEnd = false
}

func insert(_ word: String) {
var node = self
for char in word {
let index = Int(char.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
node.children[index] = Trie()
}
node = node.children[index]!
}
node.isEnd = true
}

func search(_ word: String) -> Bool {
if let node = searchPrefix(word) {
return node.isEnd
}
return false
}

func startsWith(_ prefix: String) -> Bool {
return searchPrefix(prefix) != nil
}

private func searchPrefix(_ prefix: String) -> Trie? {
var node = self
for char in prefix {
let index = Int(char.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
return nil
}
node = node.children[index]!
}
return node
}
}
/**
* Your Trie object will be instantiated and called as such:
* let trie = Trie()
* trie.insert(word);
* trie.search(word);
* trie.startsWith(prefix);
*/