500. 键盘行

https://leetcode-cn.com/problems/keyboard-row/

解法一:位运算

思路:(借鉴别人的)利用掩码(mask)

001 --> 1
010 --> 2 
100 --> 4

定义第一行“QWERTYUIOP”为1(001),第二行(“ASDFGHJKL”) 为2(010),第三行 (“ZXCVBNM”)为4(100).对每个word的每个字符,以7(111)为初始值进行与操作(AND).如果每行都在同一行,则最终结果为1,2或4.如果其中有字符来自不同行,则最终结果为0.

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        dict = [0] * 26
        for ch in 'QWERTYUIOP':
            dict[ord(ch) - 65] = 1  #‘A’的asc为65
        for ch in 'ASDFGHJKL':
            dict[ord(ch) - 65] = 2
        for ch in 'ZXCVBNM':
            dict[ord(ch) - 65] = 4
        res = []
        for word in words:
            tmp = 7     #初始111
            for ch in word:
                tmp &= dict[ord(ch.upper()) - 65]
            if tmp != 0:
                res.append(word)
        return res

最后更新于