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.

Example 1:

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

题意:

给出n个字符串,从而判断每个字符串中的字符石头来自美式键盘上的同一行,若来自同一行,返回该string。


代码:

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        
        dict = {'Q':1, 'W':1, 'E':1, 'R':1, 'T':1, 'Y':1, 'U':1, 'I':1, 'O':1, 'P':1,
               'A':2, 'S':2, 'D':2, 'F':2, 'G':2, 'H':2, 'J':2, 'K':2, 'L':2,
               'Z':3, 'X':3, 'C':3, 'V':3, 'B':3, 'N':3, 'M':3,
               }                                                                                //定义一个字典
        
        n = len(words)                                                   //统计字符串长度
        i = 0
        while i < n :
            flag = 1
            ni = len(words[i])
            if ni > 0 :
                if ord(words[i][0]) <=122 and ord(words[i][0]) >= 97 :     //小写字符的处理
                    x = dict[chr(ord(words[i][0])-32)]
                else :
                    x = dict[words[i][0]]
            
                j = 1                       //比较字符串里的每个字符
                while j < ni :
                    if ord(words[i][j]) <=122 and ord(words[i][j]) >= 97 :       //小写字符处理
                        y = dict[chr(ord(words[i][j])-32)]
                    else :
                        y = dict[words[i][j]]
                    if x != y :                       //如果有字符不在同一行,则删除该字符串
                        del words[i]
                        flag = 0
                        break
                    j += 1
            if flag == 0 :
                n -= 1
                i -= 1
            i += 1
        return words


网上其他的处理方法,充分利用python的子集功能:

class Solution2(object):
  def findWords(self, words):
    row1, row2, row3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm');
    ret = [];
    for word in words:
      w = set(word.lower());
      if w.issubset(row1) or w.issubset(row2) or w.issubset(row3):
        ret.append(word);
    return ret;

厉害!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值