題目地址:
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;
}
}
時間複雜度,空間。