- 500.键盘行
- 题目描述
- 思路:模拟
- Java实现
- Python实现
500.键盘行 题目描述
键盘行
思路:模拟
根据题意进行模拟,将键盘上三行字母打表分类,依次检查words中的单词中每个字符是否都属于同一编号,若属于同一编号,则将其单词加入答案。
Java实现class Solution {
static String[] ss = new String[]{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
static int[] hash = new int[26];
static {
for (int i=0; i < ss.length; i++) {
for (char c: ss[i].toCharArray()) hash[c-'a'] = i;
}
}
public String[] findWords(String[] words) {
List list = new ArrayList<>();
out: for (String word: words) {
int t = -1;
for (char c: word.toCharArray()) {
c = Character.toLowerCase(c);
if (t == -1) t = hash[c-'a'];
else if (t != hash[c-'a']) continue out;
}
list.add(word);
}
return list.toArray(new String[list.size()]);
}
}
Python实现
LINES = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
class Solution:
def findWords(self, words: List[str]) -> List[str]:
return [word for word in words if any(set(word.lower()).issubset(LINE) for LINE in LINES)]



