[leetcode]30. Substring with Concatenation of All Words

本文介绍了一个LeetCode上的经典题目——寻找由给定单词列表拼接而成的所有子串的起始索引。通过C++实现了一个解决方案,详细展示了如何遍历字符串并检查每个可能的子串是否符合要求。

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

链接:https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/

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 = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        if (words.empty())
            return vector<int>();

        vector<int> ret;
        //记录所给words中每个单词的出现次数
        map<string, int> word_count;


        //每个单词的长度相同
        int word_size = strlen(words[0].c_str());
        int word_nums = words.size();
        //所给匹配字符串的长度
        int s_len = strlen(s.c_str());

        for (int i = 0; i < word_nums; i++)
            ++word_count[words[i]];

        int i, j;
        map<string, int> temp_count;
        for (i = 0; i < s_len - word_nums*word_size + 1; ++i)
        {
            temp_count.clear();
            for (j = 0; j < word_nums; j++)
            {
                //检验当前单词是否属于words以及出现的次数是否一致
                string word = s.substr(i + j*word_size, word_size);
                if (word_count.find(word) != word_count.end())
                {
                    ++temp_count[word];
                    //如果出现的次数与words不一致,则返回错误
                    if (temp_count[word] > word_count[word])
                        break;
                }
                else{
                    break;
                }               
            }
            //所有words内的单词,在i起始位置都出现,则将下标i存入结果的vector中
            if (j == word_nums)
            {
                ret.push_back(i);
            }
        }
        return ret;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值