[LeetCode] 500. Keyboard Row 键盘行
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

Example:
Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
给一组单词,返回哪些单词是由键盘上的一行字母组成的。
Java:
public class Solution {
public String[] findWords(String[] words) {
String[] strs = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i<strs.length; i++){
for(char c: strs[i].toCharArray()){
map.put(c, i);//put <char, rowIndex> pair into the map
}
}
List<String> res = new LinkedList<>();
for(String w: words){
if(w.equals("")) continue;
int index = map.get(w.toUpperCase().charAt(0));
for(char c: w.toUpperCase().toCharArray()){
if(map.get(c)!=index){
index = -1; //don't need a boolean flag.
break;
}
}
if(index!=-1) res.add(w);//if index != -1, this is a valid string
}
return res.toArray(new String[0]);
}
}
Java: 1-Line Solution via Regex and Stream
public String[] findWords(String[] words) {
return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);
}
Python: wo
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
rows = {'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, 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, \
'n': 3, 'm': 3}
res = []
for word in words:
row = None
one_line = True
for c in word:
if not row:
row = rows[c.lower()]
elif row != rows[c.lower()]:
one_line = False
break
if one_line:
res.append(word)
return res
Python:
def findWords(self, words):
line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
ret = []
for word in words:
w = set(word.lower())
if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
ret.append(word)
return ret
C++:
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> res;
unordered_set<char> row1{'q','w','e','r','t','y','u','i','o','p'};
unordered_set<char> row2{'a','s','d','f','g','h','j','k','l'};
unordered_set<char> row3{'z','x','c','v','b','n','m'};
for (string word : words) {
int one = 0, two = 0, three = 0;
for (char c : word) {
if (c < 'a') c += 32;
if (row1.count(c)) one = 1;
if (row2.count(c)) two = 1;
if (row3.count(c)) three = 1;
if (one + two + three > 1) break;
}
if (one + two + three == 1) res.push_back(word);
}
return res;
}
};

浙公网安备 33010602011771号