500. 键盘行

题目网址:https://leetcode-cn.com/problems/keyboard-row/hints/

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

American keyboard

示例1:

输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]

注意:

    你可以重复使用键盘上同一字符。
    你可以假设输入的字符串将只包含字母
 
代码关键理解:当前字母是否和上一个字母同在一个键盘行
class Solution:
    def findWords(self, words):      
        line1="qwertyuiop"
        line2="asdfghjkl"
        line3="zxcvbnm"
        results=[]
        
        for string in words:            
            string2 = string.lower()
            
            inLine = 0
            appendStr2 = True
            for s in string2:                
                if inLine==0:
                    if s in line1:
                        inLine = 1
                    elif s in line2:                        
                        inLine = 2                    
                    else:
                        inLine = 3
                else:
                    if ((s in line1) and inLine!=1) or ((s in line2) and inLine!=2) or ((s in line3) and inLine!=3) :
                        appendStr2 = False
                        break   
            if appendStr2:
                results.append(string)
                                                               
        return results

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!