【leetcode刷题】30. Substring with Concatenation of All Words

原题链接
https://leetcode.com/problems/substring-with-concatenation-of-all-words/
解题思路
string中如果有满足条件的substring,则一定有以下特点:
1、substring的长度=words中所有word的总长度
2、substring中的每个word出现频次与words中的频次相同
因此可以以word length*num_word的长度作为一个大窗口,以word length作为一个小窗口,从string[0]开始,取substring,再按照上述两规则判断substring是否符合规范,是则将起始位置输出,否则起始位置后移1
在这里插入图片描述代码

class Solution(object):
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        # count the frequency of the occurrence of of each word in word list
        if len(words)==0:
            return []
        word_dict = {}
        for item in words:
            if item not in word_dict.keys():
                word_dict[item] = 1
            else:
                word_dict[item] += 1

        word_len = len(words[0]) # the length of word in words
        string_len = len(s)
        num_word = len(words)

        word_start = 0
        s_sub_start = 0
        word_end = word_start + word_len

        result = []
        while s_sub_start < string_len-word_len*num_word+1:
            count_dict = {}
            word = s[word_start:word_end]
            if word in words:
                count_dict[word] = 1
                # if count_dict[word] > word_dict[word]:
                #     break
                while word_end < s_sub_start + num_word * word_len:
                    word_start += word_len
                    word_end += word_len
                    word = s[word_start:word_end]
                    if word not in words:
                        break
                    else:
                        if word in count_dict.keys():
                            count_dict[word] += 1
                        else:
                            count_dict[word] = 1
                        if count_dict[word] > word_dict[word]:
                            break
                if word_dict == count_dict:
                    result.append(s_sub_start)
            s_sub_start += 1
            word_start = s_sub_start
            word_end = word_start + word_len
        return result

参考:https://www.cnblogs.com/zuoyuan/p/3779978.html

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/88853788