Leetcode 500. Keyboard Row 键盘行
题目:
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
示例1:
输入: ["Hello", "Alaska", "Dad", "Peace"] 输出: ["Alaska", "Dad"]
注意:
- 你可以重复使用键盘上同一字符。
- 你可以假设输入的字符串将只包含字母。
解题思路:
创建哈希表表示键盘,然后对每一个word进行判断,确认是否为一行可以打出。
代码实现:
class Solution { public String[] findWords(String[] words) { List<String> res = new ArrayList<String>(); // 构建键盘表 String[] str = {"qwertyuiop", "asdfghjkl", "zxcvbnm"}; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < str.length; i ++) { for (char c : str[i].toCharArray()) { map.put(c, i); } } // 判断 for (String word : words) { boolean check = true; char[] chs = word.toCharArray(); int first = map.get(Character.toLowerCase(chs[0])); for (int j = 1; j < chs.length; j ++) { if (map.get(Character.toLowerCase(chs[j])) != first) { check = false; break; } } if (check) res.add(word); } return res.toArray(new String[0]); } }