Substring with Concatenation of All Words

本文针对LeetCode上的一道难题Substring with Concatenation of All Words进行了详细的解析,介绍了如何通过使用哈希表的方法来解决该问题,并给出了具体的实现代码。

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

每日算法——leetcode系列


问题 Substring with Concatenation of All Words

Difficulty: Hard

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.

For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {

    }
};

翻译

与所有单词相关联的字串

难度系数:困难
给定一个字符串s和一些长度相同的单词words,找出s的与words中所有单词(words每个单词只出现一次)串联一起(words中组成串联串的单词的顺序随意)的字符串匹配的所有起始索引,子串要与串联串完全匹配,中间不能有其他字符。

思路

这题对我来说就是理解题意。
先把words中每个单词,以words中每个单词为key, 单词出现的次数为value放入map表中
再在s中每次取三个来去map表找,如果找到则找下三个,如果没找到,则s索引回溯到找到的第一个的索引 + 1。

代码


class Solution {
public:
    vector<int> findSubstring(string s, vector<string> &words) {

        vector<int> result;
        if (s.size() <= 0 || words.size() <= 0) {
            return result;
        }

        if (s.size() < words.size() * words[0].size()) {
            return result;
        }

        int m = static_cast<int>(s.size());
        int n = static_cast<int>(words.size());
        int l = static_cast<int>(words[0].size());

        unordered_map<string, int> wordMap;
        for (int i = 0; i < n; ++i) {
            if (wordMap.find(words[i]) != wordMap.end()) {
                wordMap[words[i]]++;
            } else {
                wordMap[words[i]] = 1;
            }
        }

        unordered_map<string, int> bakWordMap = wordMap;
        int fisrtIdnex = 0;
        for (int j = 0; j <= m - l;) {
            string word = s.substr(j, l);
            if (wordMap.find(word) == wordMap.end()) {
                j = ++fisrtIdnex;
                wordMap = bakWordMap;
                continue;
            }
            j += l;
            wordMap.at(word)--;
            if (wordMap.at(word) == 0) {
                wordMap.erase(word);
            }

            if (wordMap.empty()) {
                result.push_back(fisrtIdnex);
                wordMap = bakWordMap;
            }
        }

        return result;
    }

};

注: 这个本地测试可以, 但提交提示超时, 再考虑下其他的办法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值