Leecode #30 Substring with Concatenation of All Words

本文详细解析了LeetCode第30题的算法思路与实现代码,旨在帮助读者理解和掌握如何在给定字符串中寻找由指定单词组合而成的子串的起始索引。

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

一、 问题描述

Leecode第三十题,题目为:

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: []

问题理解为

给定一个字符串,s,和一系列单词,它们长度相同。在s中找到所有子字符串的起始索引,该索引是单词中每个单词的一次连接,并且不包含任何中间字符。

例1:
输入:
s =“barfoothefoobarman”,
words= (“foo”、“bar”)
输出:(0,9)

示例2:
输入:
s =“wordgoodgoodgoodbestword”,
words=[“word”,“good”,“best”,“word”)
输出:[]

说明:

从索引0和索引9开始的子字符串分别是“barfoor”和“foobar”。
输出顺序无关紧要,返回[9,0]也可以。

二、算法思路
1、
2、

三、实现代码


class Solution {
    
public:
    
    vector<int> findSubstring(string S, vector<string> &L) {
        int l_size = L.size();
        
        if (l_size <= 0) {
            return vector<int>();
        }
        
        vector<int> result;
        map<string, int> wordcount;
        int wordlengh = L[0].size();
        int i, j;
        
        for (i = 0; i < l_size; ++i) {
            ++wordcount[L[i]];
        }
        
        map<string, int> counting;
        
        for (i = 0; i <= (int)S.length() - (l_size * wordlengh); ++i) {
            counting.clear();
            
            for (j = 0; j < l_size; ++j) {
                string word = S.substr(i + j * wordlengh, wordlengh);
                
                if (wordcount.find(word) != wordcount.end()) {
                    ++counting[word];
                    
                    if (counting[word] > wordcount[word]) {
                        break;
                    }
                }
                else {
                    break;
                }
            }
            
            if (j == l_size) {
                result.push_back(i);
            }
        }
        
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值