leetcode30 Substring with Concatenation of All Words

该博客介绍了如何使用双指针法解决LeetCode 30题,即找到字符串中所有由给定相同长度单词组成的无间隔子串的起始索引。通过一个哈希映射记录单词出现次数,从左到右遍历字符串,判断当前子串是否符合题目要求。示例展示了不同输入下的输出结果。
摘要由CSDN通过智能技术生成

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoo” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:

Input:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
Output: []

才用双指针法,记录两个位置一个是子串的开始位置,一个是子串的末尾。由于我们要查询的是words的全排列,所以需要一个hashmap记录下words当中每一个Word的出现次数。然后从left位置开始遍历,如果right位置对应的字符串在words当中出现过,并且此时在hashmap中的值仍然大于1,那我们就把right后移,并且将hash_map中对应的word减1。如果right位置在words中出现过,但是其在hash_map当中的值为0或者right位置在words中没有出现,那就将left后移一个位置,重新开始。具体实现代码如下:

def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not s or not words:
            return []
        solution = []
        word_dict = {}
        word_dict = dict(collections.Counter(words))
        length = len(words[0])
        for index in range(len(s)-length*len(words)+1):
            temp_dict = word_dict.copy()
            for i in range(len(words)):
                new_word = s[index+length*i: index+length*i+length]
                if new_word in temp_dict:
                    if temp_dict[new_word] > 1:
                        temp_dict[new_word] -= 1
                    else:
                        temp_dict.pop(new_word)
                else:
                    break
                if not temp_dict:
                    solution.append(index)
        return solution
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值