LeetCode:30. Substring with Concatenation of All Words - Python

189 篇文章 3 订阅
151 篇文章 2 订阅

问题描述:

30. 串联所有单词的子串

给定一个字符串s和一些长度相同的单词 words。在s中找出可以恰好串联 words 中所有单词的子串的起始位置。

注意子串要与words中的单词完全匹配,中间不能有其他字符,但不需要考虑words中单词串联的顺序。

示例 1:

输入:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出: [0,9]
解释: 从索引 0 和 9 开始的子串分别是 “barfoor” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:
s = “wordgoodstudentgoodword”,
words = [“word”,“student”]
输出: []

问题分析:

这个题目看着很复杂,其实不难,可以用滑动窗口的方法解决,先把 words 中的所有单词进行放到一个字典中,然后扫描字符串s,一个窗口一个窗口的统计分析,把符合的小窗口的起始位置保存结果变量里,即可。

Python3实现:

# @Time   :2018/09/24
# @Author :Liu


class Solution:
    def findSubstring(self, s, words):

        if len(words) == 0: return []
        wordsDict = {}
        for word in words:  # 统计每个单词出现的个数
            if word not in wordsDict:
                wordsDict[word] = 1
            else:
                wordsDict[word] += 1

        n, m, k = len(s), len(words[0]), len(words)  # n, m, k 分别表示,字符串的长度,单词的长度,单词的个数
        res = []

        for i in range(n - m * k + 1):  # 选择一个区间或者窗口
            j = 0
            cur_dict = {}

            while j < k:
                word = s[i + m * j:i + m * j + m]  # 区间内选择一个单词
                if word not in wordsDict:  # 出现不存在的单词,直接结束本此区间
                    break
                if word not in cur_dict:
                    cur_dict[word] = 1
                else:
                    cur_dict[word] += 1
                if cur_dict[word] > wordsDict[word]:  # 某个单词大于所需,则直接结束本此区间
                    break
                j += 1  # 单词数加一

            print(j)
            if j == k: res.append(i)  # 记录起始位置

        return res


if __name__ == '__main__':
    solu = Solution()
    s, words = 'barfoothefoobarman', ['foo', 'bar']
    print(solu.findSubstring(s, words))

方法二

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        from collections import Counter
        if not s or not words:return []
        one_word = len(words[0])
        all_len = len(words) * one_word
        n = len(s)
        words = Counter(words)
        res = []

        for i in range(0, n - all_len + 1):
            tmp = s[i:i+all_len]
            c_tmp = []
            
            for j in range(0, all_len, one_word):
                c_tmp.append(tmp[j:j+one_word])
            if Counter(c_tmp) == words:
                res.append(i)
        return res

声明: 总结学习,有问题可以批评指正,大神可以略过哦
题目链接:leetcode-cn.com/problems/substring-with-concatenation-of-all-words/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值