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(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
rows = ["qwertyuiop", "asdfghjkl","zxcvbnm"]
output = []
for word in words:
#word = word.lower()
for row in rows:
#row = row.lower()
num = 0
for char in word.lower():
for row_char in row.lower():
if char == row_char:
num += 1
break #这里加个这个,匹配到一个以后推出本次循环
if num == len(word):
output.append(word)
break
return output
这种应该是最笨的方法了,其中需要把判断的字符都转换为小写(string.lower() ),排名在34%。
解2:
还可以用set()来解,因为set()是所有出现过的字符,如果两个集合的交集等于单词的集合,那么这两个字符就匹配。
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