英文原文
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
- the first row consists of the characters
"qwertyuiop", - the second row consists of the characters
"asdfghjkl", and - the third row consists of the characters
"zxcvbnm".
Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"] Output: ["Alaska","Dad"]
Example 2:
Input: words = ["omk"] Output: []
Example 3:
Input: words = ["adsdf","sfd"] Output: ["adsdf","sfd"]
Constraints:
1 <= words.length <= 201 <= words[i].length <= 100words[i]consists of English letters (both lowercase and uppercase).
中文题目
给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
- 第一行由字符
"qwertyuiop"组成。 - 第二行由字符
"asdfghjkl"组成。 - 第三行由字符
"zxcvbnm"组成。

示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"] 输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"] 输出:[]
示例 3:
输入:words = ["adsdf","sfd"] 输出:["adsdf","sfd"]
提示:
1 <= words.length <= 201 <= words[i].length <= 100words[i]由英文字母(小写和大写字母)组成
通过代码
高赞题解
模拟
根据题意,进行模拟即可。
先将键盘上的三行字母进行打表分类,依次检查 $words$ 中的单词中的每个字符是否都属于同一编号,若属于同一编号,则将其单词加入答案。
代码:
[]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<String> list = new ArrayList<>(); out:for (String w : words) { int t = -1; for (char c : w.toCharArray()) { c = Character.toLowerCase(c); if (t == -1) t = hash[c - 'a']; else if (t != hash[c - 'a']) continue out; } list.add(w); } return list.toArray(new String[list.size()]); } }
- 时间复杂度:$O(\sum_{i = 0}^{n - 1} words[i].length)$
- 空间复杂度:
toCharArray会拷贝新数组,不使用toCharArray,使用charAt的话,复杂度为 $O(C)$,$C$ 为常数,固定为 $26$;否则复杂度为 $O(\sum_{i = 0}^{n - 1} words[i].length)$
其他「模拟」相关内容
题目简单?考虑加练如下「模拟」题目 🍭🍭
注:以上目录整理来自 wiki,任何形式的转载引用请保留出处。
最后
如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ (“▔□▔)/
也欢迎你 关注我(公主号后台回复「送书」即可参与长期看题解学算法送实体书活动)或 加入「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。
所有题解已经加入 刷题指南,欢迎 star 哦 ~
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 52236 | 70201 | 74.4% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|