题目地址:
https://leetcode.com/problems/keyboard-row/
给定一个字符串数组,返回其中可以由键盘中其中一行打出来的所有字符串。
先把键盘的每一行存入三个哈希表,然后遍历数组。可以用一个数的二进制位来记录每个字符串用了那几行,然后判断一下是否等于、或者即可。代码如下:
import java.util.*;
public class Solution {
public String[] findWords(String[] words) {
List<String> ans = new ArrayList<>();
Set<Character>[] sets = (HashSet<Character>[]) new HashSet[3];
String[] rows = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
for (int i = 0; i < rows.length; i++) {
sets[i] = new HashSet<>();
for (int j = 0; j < rows[i].length(); j++) {
sets[i].add(rows[i].charAt(j));
}
}
for (int i = 0; i < words.length; i++) {
int row = 0;
for (int j = 0; j < words[i].length(); j++) {
char ch = Character.toLowerCase(words[i].charAt(j));
// 如果发现ch在其中某一行,就将那一行的编号的二进制位置为1
if (sets[0].contains(ch)) {
row |= 1;
}
if (sets[1].contains(ch)) {
row |= 2;
}
if (sets[2].contains(ch)) {
row |= 8;
}
}
if (row == 1 || row == 2 || row == 8) {
ans.add(words[i]);
}
}
String[] res = new String[ans.size()];
for (int i = 0; i < res.length; i++) {
res[i] = ans.get(i);
}
return res;
}
}
时间复杂度,空间。