DEV Community

Sergey Leschev
Sergey Leschev

Posted on • Edited on

LeetCode: 211. Design Add and Search Words Data Structure (and others)

// Solution @ Sergey Leschev

class TrieNode {
    var children: [Character: TrieNode]
    var isWord: Bool

    init() {
        children = [:]
        isWord = false
    }
}

class WordDictionary {
    var root: TrieNode

    init() {
        root = TrieNode()
    }

    func addWord(_ word: String) {
        var node = root
        for c in word {
            if let child = node.children[c] {
                node = child
            } else {
                let child = TrieNode()
                node.children[c] = child
                node = child
            }
        }
        node.isWord = true
    }

    func search(_ word: String) -> Bool {
        return searchHelper(Array(word), 0, root)
    }

    private func searchHelper(_ word: [Character], _ index: Int, _ node: TrieNode) -> Bool {
        if index == word.count {
            return node.isWord
        }

        let c = word[index]

        if c != "." {
            if let child = node.children[c] {
                return searchHelper(word, index+1, child)
            }
            return false
        } else {
            for child in node.children.values {
                if searchHelper(word, index+1, child) {
                    return true
                }
            }
            return false
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

My LeetCode Solutions / Swift
https://github.com/sergeyleschev/leetcode-swift

My LeetCode Solutions / TypeScript
https://github.com/sergeyleschev/leetcode-typescript


Contacts
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

πŸ›©οΈ #startups #management #cto #swift #typescript #database
πŸ“§ Email: sergey.leschev@gmail.com
πŸ‘‹ LinkedIn: https://linkedin.com/in/sergeyleschev/
πŸ‘‹ LeetCode: https://leetcode.com/sergeyleschev/
πŸ‘‹ Twitter: https://twitter.com/sergeyleschev
πŸ‘‹ Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev

Top comments (0)