Skip to content

Commit b9e52e2

Browse files
committed
[String] Optimize syntax for Keyboard Row
1 parent 813b46e commit b9e52e2

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

String/KeyboardRow.swift

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* Question Link: https://leetcode.com/problems/keyboard-row/
3-
* Primary idea: Convert each row to set to determine the word is subset or not.
3+
* Primary idea: Use filter to determine the word is subset or not.
44
*
55
* Note: You can also use intersect() or union() functions to solve this problem.
66
*
@@ -10,26 +10,14 @@
1010

1111
class KeyboardRow {
1212
func findWords(_ words: [String]) -> [String] {
13-
var res = [String]()
14-
15-
let rowOne = Set("qwertyuiop".characters), rowTwo = Set("asdfghjkl".characters), rowThree = Set("zxcvbnm".characters)
16-
17-
for word in words {
18-
if isInRow(word, rowOne) || isInRow(word, rowTwo) || isInRow(word, rowThree) {
19-
res.append(word)
20-
}
21-
}
22-
23-
return res
13+
let rowOne = "qwertyuiop", rowTwo = "asdfghjkl", rowThree = "zxcvbnm"
14+
15+
return words.filter { word in rowOne.contains(word) || rowTwo.contains(word) || rowThree.contains(word) }
2416
}
25-
26-
fileprivate func isInRow(_ word: String, _ row: Set<Character>) -> Bool {
27-
for char in word.lowercased().characters {
28-
if !row.contains(char) {
29-
return false
30-
}
17+
18+
extension String {
19+
func contains(_ word: String) -> Bool {
20+
return word.filter { c in !self.contains(c) }.characters.count == 0
3121
}
32-
33-
return true
3422
}
3523
}

0 commit comments

Comments
 (0)