题目是这样的:
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.
给出一系列的单词,判断这些单词是否出自键盘的同一行(忽略大小写)
键盘就是标准的美式键盘:
题目中给出的例子是这样的:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
输入是一个list,输出是一个list,输出的list是所有字母在同一行的。我解决这到题目的思路是这样的:
1.将每一行的字母放一个字符串
2.遍历输入的list
3.字符串变成小写,
4.判断每一个字母属于哪一行,并将数字付给临时集合set
5.判断set的大小
具体的程序如下(python):
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
mylist = []
first = "qwertyuiop"
sencond = "asdfghjkl"
threed = "zxcvbnm"
for ii in range(len(words)):
i = (words[ii].lower())
temp = []
for j in range(len(i)):
if i[j] in first:
temp.append(1)
if i[j] in sencond:
temp.append(2)
if i[j] in threed:
temp.append(3)
if len(set(temp))==1:
mylist.append(words[ii])
return mylist
没有调整变量名(不规范),手写代码一次通过。其结果是这样的: