leetcode Day4 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.

keyboard.png

 
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.
 
中文解释:
输入一个字符串列表,如果这个字符串的字母在键盘上的位置为同一行,就输出这个字符串,否则不输出。
 
    def findWords( words):
"""
:type words: List[str]
:rtype: List[str]
"""

kb={'q':['q','w','e','r','t','y','u','i','o','p'],
'a':['a','s','d','f','g','h','j','k','l'],
'z':['z','x','c','v','b','n','m']}

rList=[]
qRow= kb['q']
aRow= kb['a']
zRow= kb['z']
for wi in words:
w=wi.lower()
i=0
l=len(w)

if w[0] in qRow:
row=qRow
if w[0] in aRow:
row=aRow
if w[0] in zRow:
row=zRow

#row=kb[w[0]]
for i in range(len(w)):
if w[i] not in row:
break
else:
if i==l-1:
rList.append(wi)
return rList

解释:
首先将字母转换为统一的小写字母,然后根据首字母确定该字符串会属于键盘上的哪一列,因为键盘上只有3列,分别为q,a,z行,如果确定属于q行,接下来将剩下的字符一直在q行内循环,一旦遇到不在q行,就退出这一次的循环,进行下一个字符串的判断。
 

0 个评论

要回复文章请先登录注册