给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。
示例:
输入:
S = “abcde”
words = [“a”, “bb”, “acd”, “ace”]
输出: 3
解释: 有三个是 S 的子序列的单词: “a”, “acd”, “ace”。
链接:https://leetcode.com/problems/number-of-matching-subsequences/
解题思路:
桶的思想:建立26个桶,每个桶以一个小写字母命名,将words中的单词按照首字母放入相应的桶中,遍历S,每扫描到一个字母,检查对应的桶中是否有单词,如果有,将该桶中所有单词的第一个字母去除,按照第二个字母重新分配到相应的桶中,待S扫描完后,检查桶中剩余的单词就是未被匹配的单词。
我的代码:
class Solution(object):
def numMatchingSubseq(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
bucket = [[] for i in range(26)]
def insert_bucket(word, bucket):
if word:
bucket[ord(word[0]) - ord('a')].append(word)
# 初始单词入桶
for word in words:
insert_bucket(word, bucket)
# 扫描S,过滤桶中单词
for s in S:
l = len(bucket[ord(s) - ord('a')])
i = 0
while i < l and bucket[ord(s) - ord('a')]:
w = bucket[ord(s) - ord('a')].pop(0)[1:]
insert_bucket(w, bucket)
i += 1
# 统计桶中剩余元素
cur = 0
for b in bucket:
cur += len(b)
return len(words) - cur
Time: O(S.length+∑words[i].length)
Space: O(words.length)
难度:中等