Given a List of words, return the words that can is typed using letters of alphabet on only one row ' s of American keyboard Like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
character in the keyboard more than once.
You may assume the input string would be only contain letters of alphabet.
This title describes:
Given some words, let's find out which words in these words are all letters on the same line of the keyboard
QWERTYUIOP is the first line of the keyboard
ASDFGHJKL is the second line of the keyboard
ZXCVBNM is the third line of the keyboard
It's really a headache to get this problem--do you want to traverse each letter of the word??
Later, referring to the ideas of other great gods, there are basically two kinds of ideas, one is the regular expression match, the other is the set thought.
I used a collection of ideas. Save all the letters of a keyboard line with three sets.
When given a word let's see if this word is a subset of one of these three sets, and if so, the word satisfies the letter in a row
My Code:
1 classsolution (object):2 deffindwords (self, words):3 """4 : Type WORDS:LIST[STR]5 : Rtype:list[str]6 """7Q,a,z = Set ("QWERTYUIOP"), Set ("ASDFGHJKL"), Set ("zxcvbnm")8res = []9 forStrinchwords:TenLSet =Set (Str.lower ()) One ifLset.issubset (q)orLset.issubset (a)orLset.issubset (z): A res.append (str) - returnRes - the - - if __name__=='__main__': -s =solution () +res = S.findwords (["Hello","Alaska","Dad","Peace"]) - Print(RES)
Leetcode algorithm: Keyboard Row