数据结构【字符串(子集)、循环、哈希表】| leetcode 500. 键盘行(简单)

13 篇文章 0 订阅
1 篇文章 0 订阅

题目链接:https://leetcode.cn/problems/keyboard-row/

方法一:

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        lst = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
        res = []
        for word in words:  # word = 'hello'
            length = len(word)
            for s in lst:   # s = "qwertyuiop"
                count = 0
                for i in word.lower():  # i = 'h'
                    if i in s:
                        count += 1
                    else:
                        break
                if length == count:
                    res.append(word)
        return res

方法二:a.issubset(b)表示求字符串a是否是b的子集。

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
		# 方法二:求字符串交集
        line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
        ret = []
        for word in words:
            w = set(word.lower())
            if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
                ret.append(word)
        return ret

方法三:哈希表

代码链接:https://leetcode.cn/problems/keyboard-row/solution/-by-liupengsay-61iv/

思路:

  • 首先将keyboard映射为哈希表,键为字母,值为所在行索引。
  • 然后遍历words中每个字母,是否等于第一个字母所在行。
keyboard = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
row = dict()
for i, string in enumerate(keyboard):
    for w in string:
        row[w] = i


class Solution:
    def check(self, word):
        group = row[word[0]]
        for va in word[1:]:
            if row[va] != group:
                return False
        return True
    
    def findWords(self, words: List[str]) -> List[str]:
        return [word for word in words if self.check(word.lower())]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值