题目
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。
示例:输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
解答
class Solution {public String[] findWords(String[] words) {char[][] keyboard = {{'1', '1'}// 第一行,大写字母,{'Q', '1'},{'W', '1'},{'E', '1'},{'R', '1'},{'T', '1'},{'Y', '1'},{'U', '1'},{'I', '1'},{'O', '1'},{'P', '1'}// 第一行,小写字母,{'q', '1'},{'w', '1'},{'e', '1'},{'r', '1'},{'t', '1'},{'y', '1'},{'u', '1'},{'i', '1'},{'o', '1'},{'p', '1'}// 第二行,大写字母,{'A', '2'},{'S', '2'},{'D', '2'},{'F', '2'},{'G', '2'},{'H', '2'},{'J', '2'},{'K', '2'},{'L', '2'}// 第二行,小写字母,{'a', '2'},{'s', '2'},{'d', '2'},{'f', '2'},{'g', '2'},{'h', '2'},{'j', '2'},{'k', '2'},{'l', '2'}// 第三行,大写字母,{'Z', '3'},{'X', '3'},{'C', '3'},{'V', '3'},{'B', '3'},{'N', '3'},{'M', '3'}// 第三行,小写字母,{'z', '3'},{'x', '3'},{'c', '3'},{'v', '3'},{'b', '3'},{'n', '3'},{'m', '3'}};StringBuilder sb = new StringBuilder();for (int i = 0; i < words.length; ++i) {String word = words[i];if (word.isEmpty()) {continue;}int length = word.length();int level = 0;int lastLevel = 0;boolean found = false;for (int j = 0; j < length; ++j) {char c = word.charAt(j);for (int k = 0; k < keyboard.length; ++k) {if (keyboard[k][0] == c) {level = keyboard[k][1];break;}}if (j == 0) {lastLevel = level;}else if (lastLevel != level){found = true;break;}}if (found) {continue;}sb.append(word).append(",");}if (sb.length() == 0) {return new String[]{};}String out = sb.deleteCharAt(sb.length() - 1).toString();return out.split(",");}
}
要点
题目自身不困难,准备字母和键盘的映射关系,花了点时间。
不太适应在网页上直接输入代码,所以还是按照平常的工作习惯,在eclipse里输入代码,同时写好用例,用例通过后,再提交,对通过率非常有帮助。
准备的用例,如下
@Testpublic void test1() {String[] words = {"Hello", "Alaska", "Dad", "Peace"}; String[] values = new L500().findWords(words);assertEquals("Alaska", values[0]);assertEquals("Dad", values[1]);}@Testpublic void test2() {String[] words = {"Hello"}; String[] values = new L500().findWords(words);assertEquals(0, values.length);}@Testpublic void test3() {String[] words = {"Alaska"}; String[] values = new L500().findWords(words);assertEquals("Alaska", values[0]);}@Testpublic void test4() {String[] words = {"Hello", "", "Dad", "Peace"}; String[] values = new L500().findWords(words);assertEquals(1, values.length);assertEquals("Dad", values[0]);}@Testpublic void test5() {String[] words = {"Hello", " ", "Dad", "Peace"}; String[] values = new L500().findWords(words);assertEquals(1, values.length);assertEquals("Dad", values[0]);}