500. 键盘行

题目

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

键盘示例

美式键盘 中:

  • 第一行由字符 "qwertyuiop" 组成。
  • 第二行由字符 "asdfghjkl" 组成。
  • 第三行由字符 "zxcvbnm" 组成。

示例1:

1
2
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]

示例2:

1
2
输入:words = ["omk"]
输出:[]

示例3:

1
2
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]

提示:

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] 由英文字母(小写和大写字母)组成

解法

解法一:

打表

Java

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public String[] findWords(String[] words) {
Set<Character> first = new HashSet<>();
first.add('q');
first.add('w');
first.add('e');
first.add('r');
first.add('t');
first.add('y');
first.add('u');
first.add('i');
first.add('o');
first.add('p');
Set<Character> second = new HashSet<>();
second.add('a');
second.add('s');
second.add('d');
second.add('f');
second.add('g');
second.add('h');
second.add('j');
second.add('k');
second.add('l');
Set<Character> third = new HashSet<>();
third.add('z');
third.add('x');
third.add('c');
third.add('v');
third.add('b');
third.add('n');
third.add('m');
StringBuilder sb = new StringBuilder();
for (String word : words) {
int f = 0;
int s = 0;
int t = 0;
for (char c : word.toCharArray()) {
if (first.contains(c)) {
f = 1;
}

if (second.contains(c)) {
s = 1;
}

if (third.contains(c)) {
t = 1;
}

}
if ((t + s + f) > 1) {
continue;
}
sb.append(word).append(" ");
}
String result = sb.toString().trim();
if (0 == result.length()) {
return new String[]{};
}
return result.split(" ");
}

解法二:

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
public String[] findWords(String[] words) {
String first = "qwertyuiop";
String second = "asdfghjkl";
String third = "zxcvbnm";
List<String> result = new ArrayList<>();
for (String word : words) {
int l1 = 0;
int l2 = 0;
int l3 = 0;
for (char c : word.toCharArray()) {
String s = String.valueOf(c).toLowerCase();
if (first.contains(s)) {
l1++;
}

if (second.contains(s)) {
l2++;
}

if (third.contains(s)) {
l3++;
}
}
if (l1 == word.length() || l2 == word.length() || l3 == word.length()) {
result.add(word);
}
}
return result.toArray(new String[result.size()]);
}
0%