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 1:
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.
找字符串,该字符串的每个字母都要在美式键盘的同一行即可。
1 class Solution { 2 public: 3 vector<string> findWords(vector<string>& words) { 4 vector<string> ans = {"qwertyuiopQWERTYUIOP","asdfghjklASDFGHJKL","zxcvbnmZXCVBNM"}; 5 vector<string> findans; 6 for(auto word = words.begin();word!=words.end();word++){ 7 string s = *word; 8 int n = 0,i = 1; 9 if(ans[0].find(s[0]) != s.npos) 10 ; 11 else if(ans[1].find(s[0]) != s.npos) 12 n = 1; 13 else 14 n = 2; 15 for(;i < s.length();i++) 16 if(ans[n].find(s[i]) == s.npos) 17 break; 18 if(i == s.length()) 19 findans.push_back(s); 20 } 21 return findans; 22 } 23 };
python:
class Solution(object):
def findWords(self, words):
row1,row2,row3 = set('qwertyuiop'),set('asdfghjkl'),set('zxcvbnm')
ret = []
for word in words:
w = set(word.lower())
if w.issubset(row1) or w.issubset(row2) or w.issubset(row3):
ret.append(word)
return ret
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
a=set('qwertyuiop')
b=set('asdfghjkl')
c=set('zxcvbnm')
ans=[]
for word in words:
t=set(word.lower())
if a&t==t:
ans.append(word)
if b&t==t:
ans.append(word)
if c&t==t:
ans.append(word)
return ans

浙公网安备 33010602011771号