给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
第一行由字符 "qwertyuiop" 组成。
第二行由字符 "asdfghjkl" 组成。
第三行由字符 "zxcvbnm" 组成。
示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"]
输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"]
输出:[]
示例 3:
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]
提示:
1 <= words.length <= 20
1 <= words[i].length <= 100
words[i] 由英文字母(小写和大写字母)组成
我的思路:暴力解法
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:36.3 MB, 在所有 Java 提交中击败了63.15%的用户
通过测试用例:22 / 22
但是时间还是蛮快的,首先将键盘上三排字母放到三个HashSet中,然后将每个String数组中的字母与之比较,看在那一排中,如果都在同一排,则将其放到List集合中。最后再调用List.toArray方法将其转换为数组
pass:toArray链接
pass:HashSet和HashMap方法的区别
HashMap | HashSet |
---|---|
实现了Map接口 | 实现Set接口 |
存储键值对 | 仅存储对象 |
调用put()向map中添加元素 | 调用add()方法向Set中添加元素 |
HashMap使用键(Key)计算Hashcode | HashSet使用成员对象来计算hashcode值,对于两个对象来说hashcode可能相同,所以equals()方法用来判断对象的相等性,如果两个对象不同的话,那么返回false |
HashMap相对于HashSet较快,因为它是使用唯一的键获取对象 | HashSet较HashMap来说比较慢 |
我的代码:
class Solution {
public String[] findWords(String[] words) {
List<String>ans=new ArrayList<>();
String str1="qwertyuiopQWERTYUIOP";
String str2="asdfghjklASDFGHJKL";
String str3="zxcvbnmZXCVBNM";
Set<Character>set1=new HashSet<>();
Set<Character>set2=new HashSet<>();
Set<Character>set3=new HashSet<>();
for(int i=0;i<str1.length();++i) set1.add(str1.charAt(i));
for(int i=0;i<str2.length();++i) set2.add(str2.charAt(i));
for(int i=0;i<str3.length();++i) set3.add(str3.charAt(i));
for(String word:words){
int n1=0,n2=0,len=word.length();
char cc=word.charAt(0);
if(set1.contains(cc)) {n1=1;n2=n1;}
else if(set2.contains(cc)) {n1=2;n2=n1;}
else if(set3.contains(cc)) {n1=3;n2=n1;}
for(int i=1;i<len&&n1==n2;++i){
char c=word.charAt(i);
if(set1.contains(c)) n2=1;
else if(set2.contains(c)) n2=2;
else if(set3.contains(c)) n2=3;
}
if(n1==n2){
ans.add(word);
}
}
return ans.toArray(new String[ans.size()]);
}
}