Keyboard Row

Question

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.

American keyboard

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Tags

  • String
  • Hash

Thought

To determine whether a set is a subset of another set, you can check whether the length of the small set is equal to the length of the intersection between these two sets.

Code

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        set1 = set('qwertyuiop')
        set2 = set('asdfghjkl')
        set3 = set('zxcvbnm')
        ans = []
        for word in words:
            wordSet = set(word.lower())
            if len(wordSet) == len(wordSet & set1) or len(wordSet) == len(wordSet & set2) or len(wordSet) == len(wordSet & set3):
                ans.append(word)
        return ans

results matching ""

    No results matching ""