Swift Trie Solution, want to bring up the topic to let swift coder share solutions


  • 0
    I

    Very straight Trie application, code attached.

    I really cannot swift solutions for most leetcode problems. So I want to share a repo about all my Swift version of LeetCode probs, and you can add or modify solutions. I know some times, some companies will only let you write code in OC/Swift if you are interviewing an iOS position(Like fb, google). I think it's a good practice to start solving lc probs in swift. The repo : https://github.com/icesnakejin/LeetCode

    Solution for this problem:

    class Solution {
        class TrieNode {
            var isWord = false
            var dict = [Character: TrieNode]()
        }
        class Trie {
            var root = TrieNode()
            init (_ dict:[String] ) {
                
                for str in dict {
                    var head = root
                    for c in Array(str.characters) {
                        if let next = head.dict[c] {
                            head = next
                        } else {
                            let node = TrieNode()
                            head.dict[c] = node
                            head = node
                        }
                    }
                    if Array(str.characters).count > 0 {
                        head.isWord = true
                    }
                }
            }
            
            func findPrefix(_ word:String) -> String? {
                var result = ""
                var head = root
                
                for c in Array(word.characters) {
                    if let next = head.dict[c] {
                        result += String(c)
                        head = next
                        if head.isWord { break }
                    } else {
                        return nil
                    }
                }
                return result
            }
        }
        func replaceWords(_ dict: [String], _ sentence: String) -> String {
            let trie = Trie(dict)
            var result = ""
            let components = sentence.components(separatedBy: " ")
            for (index , com) in components.enumerated() {
                if let prefix = trie.findPrefix(com) {
                    result += prefix
                } else {
                    result += com
                }
                if index != components.count - 1 {
                    result += " "
                }
            }
            return result
        }
    }
    
    

Log in to reply
 

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