Leetcode 30.串联所有单词的子串

Time: 20191023

题目描述

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

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

示例 1:

输入:

  s = "barfoothefoobarman",
  words = ["foo","bar"]

输出:[0,9]

解释
从索引 0 和 9 开始的子串分别是 “barfoo” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:

  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]

输出:[]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路一

首先我们想一种比较直观且暴力的搜索算法。我们需要在原字符串s中找到all_len = len(words[0]) * len(words)个字符完全匹配。

所以可以用两重循环来统计单词的数量,外层循环是从0开始到len(s) - all_len(包含此下标),内层循环是统计从当前位置开始,向后切分单词并统计到字典。

将统计的字典和words数组得出的字典比较,如果满足,则将下标加入到结果中。

算法复杂度为: O ( n 2 ) O(n^2) O(n2).

代码一

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        # 输出起始位置
        # words中的单词必须全部用上
        # words中的单词有重复也要全部用上
        if not s or not words:return []
        
        len_word = len(words[0])
        def get_dic(temp_str):
            dic = {}
            for i in range(len(temp_str) // len_word):
                word = temp_str[i * len_word: (i + 1) * len_word]
                if dic.get(word) == None:
                    dic[word] = 1
                else:
                    dic[word] += 1
            return dic
        res = []
        from collections import Counter
        counter = Counter(words)
        all_len = len(words) * len_word
        size = len(s)
        # 从每个字符开始
        for i in range(size - all_len + 1):
            temp_str = s[i: i + all_len]
            # print('temp_str: ', temp_str)
            temp_dic = get_dic(temp_str)
            # print('temp_dic: ', temp_dic)
            
            if temp_dic == counter:
                res.append(i)        
            
        return res

思路二

TBD.

代码二

TBD.

END.

你可能感兴趣的:(LeetCode)