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

Total
0
Shares
// 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://www.linkedin.com/in/sergeyleschev/
👋 LeetCode: https://leetcode.com/sergeyleschev/
👋 Twitter: https://twitter.com/sergeyleschev
👋 Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io

Total
0
Shares

How To Maximize Your Website’s Potential with Effective SEO Strategies

SEO (Search Engine Optimization) is the practice of optimizing websites for search engines to increase their visibility and…

You May Also Like