算法提高之LeetCode刷题LeetCode solutionsLeetCode

Leetcode 500: Keyboard Row

2017-04-16  本文已影响65人  yarving

题目

出处
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.

代码

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
上一篇下一篇

猜你喜欢

热点阅读