leetcode 500. 键盘行(Java版)
题目
https://leetcode-cn.com/problems/keyboard-row/
题解
对于每一个单词,先确定所在键盘行数,然后验证后面的字母是否在同一行。
class Solution {
public static String[] findWords(String[] words) {
HashMap<Character, Integer> map = new HashMap<>();
map.put('q', 1);
map.put('w', 1);
map.put('e', 1);
map.put('r', 1);
map.put('t', 1);
map.put('y', 1);
map.put('u', 1);
map.put('i', 1);
map.put('o', 1);
map.put('p', 1);
map.put('a', 2);
map.put('s', 2);
map.put('d', 2);
map.put('f', 2);
map.put('g', 2);
map.put('h', 2);
map.put('j', 2);
map.put('k', 2);
map.put('l', 2);
map.put('z', 3);
map.put('x', 3);
map.put('c', 3);
map.put('v', 3);
map.put('b', 3);
map.put('n', 3);
map.put('m', 3);
List<String> list = new ArrayList<String>();
for (String word : words) {
char[] chars = word.toLowerCase().toCharArray();
int line = map.get(chars[0]);
int i;
for (i = 0; i < chars.length; i++) {
if (map.get(chars[i]) != line) break;
}
if (i == chars.length) list.add(word);
}
String[] resultArray = new String[list.size()];
resultArray = list.toArray(resultArray);
return resultArray;
}
}
还没有评论,来说两句吧...