forked from WenchaoD/LeetCode_Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyboardRow.swift
35 lines (29 loc) · 986 Bytes
/
KeyboardRow.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Question Link: https://leetcode.com/problems/keyboard-row/
* Primary idea: Convert each row to set to determine the word is subset or not.
*
* Note: You can also use intersect() or union() functions to solve this problem.
*
* Time Complexity: O(nm), Space Complexity: O(n)
*
*/
class KeyboardRow {
func findWords(_ words: [String]) -> [String] {
var res = [String]()
let rowOne = Set("qwertyuiop".characters), rowTwo = Set("asdfghjkl".characters), rowThree = Set("zxcvbnm".characters)
for word in words {
if isInRow(word, rowOne) || isInRow(word, rowTwo) || isInRow(word, rowThree) {
res.append(word)
}
}
return res
}
fileprivate func isInRow(_ word: String, _ row: Set<Character>) -> Bool {
for char in word.lowercased().characters {
if !row.contains(char) {
return false
}
}
return true
}
}