leetcode解题: Keyboard Row (500)

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.
alt text

Example 1:

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

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

解法1:

这题就是掌握一下语言中对于string查找相关的操作。
Java
Java中的string.toCharArray(),还有查找一个char是否在string里的操作string.indexOf(s) == -1

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
public class Solution {
String[] keyboards = {"qwertyuiop","asdfghjkl","zxcvbnm"};
public String[] findWords(String[] words) {
List<String> res = new ArrayList<String>();
for (String word: words) {
for (String row: keyboards) {
boolean temp = true;
for (char s: word.toLowerCase().toCharArray()) {
if (row.indexOf(s) == -1) {
temp = false;
break;
}
}
if (temp) {
res.add(word);
break;
}
}
}
String[] r = new String[res.size()];
res.toArray(r);
return r;
}
}