Skip to content

Latest commit

 

History

History
47 lines (39 loc) · 1.27 KB

0500-Keyboard Row.md

File metadata and controls

47 lines (39 loc) · 1.27 KB

Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

Example

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Solution

O(words*k+26) Time, O(26) Space:

class Solution {
    func findWords(_ words: [String]) -> [String] {
        
        var lookup : [String: Int] = [:]
        "qwertyuiop".forEach { lookup[String($0)] = 0 }
        "asdfghjkl".forEach { lookup[String($0)] = 1 }
        "zxcvbnm".forEach { lookup[String($0)] = 2 }
        
        var result : [String] = []
        for word in words {
            guard !word.isEmpty else { continue }
            let index = lookup[word.first!.lowercased()]!
            var isSameRow = true
            for char in word {
                if lookup[char.lowercased()]! != index {
                    isSameRow = false
                    break
                }
            }
            if isSameRow {
                result.append(word)
            }
        }
        return result
    }
}