Leetcode 30. Substring with Concatenation of All Words

本文介绍了一种算法,用于找出字符串s中由words列表中所有单词恰好组成的所有起始索引位置,考虑了words列表中可能存在重复单词的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 "barfoor" 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里有重复的词,为了处理这种情况,我们要记录每个词在s中出现的次数。

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        ans=[]
        wordsCount={}
        for word in words:
            if word in wordsCount:
                wordsCount[word]+=1
            else:
                wordsCount[word]=1
        if len(s)==0 or len(words)==0:
            return []
        for i in range(len(s)-len(words)*len(words[0])+1):
            wordsFind={}
            flag=0
            for k in range(len(words)):
                sub=s[i+k*len(words[0]):i+(k+1)*len(words[0])]
                if sub in wordsCount:
                    if sub in wordsFind:
                        wordsFind[sub]+=1
                    else:
                        wordsFind[sub]=1
                else:
                    flag=1
                    break
                if wordsFind[sub]>wordsCount[sub]:
                    flag=1
                    break
            if flag==0:
                ans.append(i)
        return ans

使用两个字典来保存words的数量,第一个wordsCount用来记录words中每个word出现的次数。然后s从开始遍历,每次检查的词长度为word的长度。sub如果在words中没有的话就跳出继续检查下一个,有的话就更新wordsFind,wordsFind记录的是s中word词出现的数量,每更新完一个词后要检查有没有超过words中这个词的数量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值