Leetcode 500: 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.

Leetcode 500: Keyboard Row_第1张图片
键盘示意图

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.

代码

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        top_row = list('QWERTYUIOPqwertyuiop')
        mid_row = list('ASDFGHJKLasdfghjkl')
        bot_row = list('ZXCVBNMzxcvbnm')
        
        res = []
        for word in words:
            row = 7
            for c in word:
                if c in top_row:
                    if (row & 1) == 0:
                        row = 0
                        break
                    row = 1
                elif c in mid_row:
                    if (row & 2) == 0:
                        row = 0
                        break
                    row = 2
                elif c in bot_row:
                    if (row & 4) == 0:
                        row = 0
                        break
                    row = 4
            
            if row is not 0:
                res.append(word)
                
        return res

你可能感兴趣的:(Leetcode 500: Keyboard Row)