Solution in python using set

• Here is the code

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

• class Solution(object):
def findWords(self, words):
row1 = set('QWERTYUIOP')
row2 = set('ASDFGHJKL')
row3 = set('ZXCVBNM')

wordList = []

for word in words:
string = set(word.upper())
for charSet in [row1, row2, row3]:
if string & charSet == string:
wordList.append(word)
break

return wordList

• @sdevarajk 谢谢你提供的思路

• def findWords(words):
first_row = set('qwertyuiop')
second_row = set('asdfghjkl')
last_row = set('zxcvbnm')
res = []
for w in words:
if set(w.lower()).issubset(first_row) or set(w.lower()).issubset(second_row) or set(w.lower()).issubset(last_row):
res.append(w)
return res

• @rawmy12 Nice one. Thank you for your insight

• @sdevarajk Good idea!!!

• @Gene20 yo..thanks !

• A small optimization on loop:

for word in words:
w = set(word.lower())
if (w&a==w) | (w&b==w) | (w&c == w):
ans.append(word)
return ans

• Here is the analysis into this code:
http://liqichen.com/daily-leetcode500-keyboard-row/

• @Jenniferz47 Thx~：）

• @rawmy12 Your code is very concise, thank you! Enter more than one word, and each word is a collection of a or B or C subsets, and output the word.

• Here's a solution that uses <= (issubset) instead of & (intersection), in case the elements appear in different orders in the set.

class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
qwer = set("qwertyuiop")
asdf = set("asdfghjkl")
zxcv = set("zxcvbnm")
ans = []

for word in words:
w = set(word.lower())
if w <= qwer or w <= asdf or w <=zxcv:
ans.append(word)

return ans

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.