Skip to content

Commit 88adfbd

Browse files
committed
Add solution 500
1 parent 860944c commit 88adfbd

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

500_KeyboardRow.swift

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
let row1 = "qwertyuiopQWERTYUIOP"
3+
let row2 = "asdfghjklASDFGHJKL"
4+
let row3 = "zxcvbnm(ZXCVBNM)"
5+
6+
private func row(of letter: String) -> Int {
7+
if row1.contains(letter) {
8+
return 1
9+
} else if row2.contains(letter) {
10+
return 2
11+
} else if row3.contains(letter) {
12+
return 3
13+
} else {
14+
return 0
15+
}
16+
}
17+
private func canTypeInRow(_ word: String) -> Bool {
18+
let firstLetter = String(word.first!)
19+
let firstLetterRow = row(of: firstLetter)
20+
let startIndex = word.index(after: word.startIndex)
21+
for item in word[startIndex...] {
22+
let letter = String(item)
23+
let row = self.row(of: letter)
24+
if row != firstLetterRow || row == 0 {
25+
return false
26+
}
27+
}
28+
return true
29+
}
30+
func findWords(_ words: [String]) -> [String] {
31+
32+
var results = [String]()
33+
for word in words {
34+
if word.isEmpty {
35+
continue
36+
}
37+
if canTypeInRow(word) {
38+
results.append(word)
39+
}
40+
}
41+
return results
42+
}
43+
}

0 commit comments

Comments
 (0)