我这个代码尽量没使用库函数,所以有点长;
首先三个数组来存储键盘的三行字母;
然后遍历我们的words String数组;
每次拿一个单词先转换小写英文字母,再来判断是否它的所有字母都出现在键盘期中一行;
如果出现在期中一行那么,把它存到ArrayList ,为什么ArrayList?因为如果存储普通String数组时没办法返回完全空格;
所以需要ArrayList来存储他们;
判断的时候;
我们再遍历一个单词的每一个字母是否在这个对应的一行;
注意每一个一行的要单独判断否子会出现,一个词的某个字母在一行某个字母在另外一行;
class Solution { private char[] first = {'q','w','e','r','t','y','u','i','o','p'}; private char[]second = {'a','s','d','f','g','h','j','k','l'}; private char[]third = {'z','x','c','v','b','n','m'}; public String[] findWords(String[] words) { ArrayList<String>res = new ArrayList<>(); int j = 0; for(int i = 0;i<words.length;i++){ if(isInFirst(words[i].toLowerCase())) res.add(words[i]); if(isInSecond(words[i].toLowerCase())) res.add(words[i]); if(isInThird(words[i].toLowerCase())) res.add(words[i]); } String []fin = res.toArray(new String[res.size()]); return fin; } public boolean isInFirst(String word){ for(int i = 0;i<word.length();i++){ if(!checkFir(word.charAt(i))) return false; } return true; } public boolean checkFir(char ch){ for(int i = 0;i<first.length;i++){ if(first[i]==ch) return true; } return false; } public boolean isInSecond(String word){ for(int i = 0;i<word.length();i++){ if(!checkSec(word.charAt(i))) return false; } return true; } public boolean checkSec(char ch){ for(int i = 0;i<second.length;i++){ if(second[i]==ch) return true; } return false; } public boolean isInThird(String word){ for(int i = 0;i<word.length();i++){ if(!checkThir(word.charAt(i))) return false; } return true; } public boolean checkThir(char ch){ for(int i = 0;i<third.length;i++){ if(third[i]==ch) return true; } return false; } }