Swift solution O(n^2)... 19ms runtime


  • 0
    E
    func findWords(_ words: [String]) -> [String] {
            let top = Set(["q","w","e","r","t","y","u","i","o","p"])
            let mid = Set(["a","s","d","f","g","h","j","k","l"])
            let bottom = Set(["z","x","c","v","b","n","m"])
        
            var results = [String]()
        
            for word in words {
                let charArray = word.lowercased().characters.map {String($0)}
                
                var targetRow: Set<String>
                
                if top.contains(charArray.first!) {
                    targetRow = top
                } else if mid.contains(charArray.first!) {
                    targetRow = mid
                } else {
                    targetRow = bottom
                }
            
                var isValid = true
                for char in charArray {
                    if targetRow.contains(char) == false {
                        isValid = false
                        break
                    }
                }
            
                if isValid {
                    results.append(word)
                }
            
            }
        
            return results
        }

Log in to reply
 

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