Swift solution


  • 0
    public struct WordNode {
        var isLeaf: Bool
        var children: [WordNode?]
        
        public init() {
            self.isLeaf = false
            self.children = [WordNode?]()
        }
    }
    
    public class WordDictionary {
        var root: WordNode
        
        public init() {
            self.root = WordNode()
        }
        
        public func addWord(_ word: String) {
            let characters = Array(word.characters)
            addWord(characters, 0, &self.root)
        }
        
        func addWord(_ characters: [Character], _ index: Int, _ parent: inout WordNode) {
            let character = characters[index]
            let position = String(character).asciiValueOfCharacter - "a".asciiValueOfCharacter
            var node = parent.children[position]
            if node == nil {
                node = WordNode()
                parent.children[position] = node
            }
            if characters.count == index + 1 {
                node!.isLeaf = true
                return
            }
            addWord(characters, index + 1, &node!)
        }
        
        public func search(_ word: String) -> Bool {
            let characters = Array(word.characters)
            return search(characters, 0, &self.root)
        }
        
        func search(_ characters: [Character], _ index: Int, _ parent: inout WordNode) -> Bool {
            if index == characters.count {
                return parent.isLeaf
            }
            
            let childNodes = parent.children
            let character = characters[index]
            if character == "." {
                for node in childNodes {
                    if var node = node {
                        if search(characters, index + 1, &node) {
                            return true
                        }
                    }
                }
                return false
            }
            
            guard var node = childNodes[String(character).asciiValueOfCharacter - "a".asciiValueOfCharacter] else {
                return false
            }
            return search(characters, index + 1, &node)
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.