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.
分析:判断字符串字符是否串行
给出N个字符串,从而判断每个字符串中的字符是否来自美式键盘上的同一行,若来自同一行则返回该string
解答:
class Solution(object):
def findWords(self, words):
:type words: List[str]
:rtype: List[str]
dict = {'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,
}
n = len(words)
i = 0
while i < n :
flag = 1
ni = len(words[i])
if ni > 0 :
if ord(words[i][0]) <=122 and ord(words[i][0]) >= 97 : //小写字符的处理
x = dict[chr(ord(words[i][0])-32)]
else :
x = dict[words[i][0]]
j = 1
while j < ni :
if ord(words[i][j]) <=122 and ord(words[i][j]) >= 97 : //小写字符处理
y = dict[chr(ord(words[i][j])-32)]
else :
y = dict[words[i][j]]
if x != y : //如果有字符不在同一行,则删除该字符串
del words[i]
flag = 0
break
j += 1
if flag == 0 :
n -= 1
i -= 1
i += 1
return words
def findWords(self, words):
:type words: List[str]
:rtype: List[str]
dict = {'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,
}
n = len(words)
i = 0
while i < n :
flag = 1
ni = len(words[i])
if ni > 0 :
if ord(words[i][0]) <=122 and ord(words[i][0]) >= 97 : //小写字符的处理
x = dict[chr(ord(words[i][0])-32)]
else :
x = dict[words[i][0]]
j = 1
while j < ni :
if ord(words[i][j]) <=122 and ord(words[i][j]) >= 97 : //小写字符处理
y = dict[chr(ord(words[i][j])-32)]
else :
y = dict[words[i][j]]
if x != y : //如果有字符不在同一行,则删除该字符串
del words[i]
flag = 0
break
j += 1
if flag == 0 :
n -= 1
i -= 1
i += 1
return words