LeetCode——Substring with Concatenation of All Words

本文探讨了如何通过枚举方法在给定字符串中找到由特定单词组成的子串,并且这些单词在子串中恰好出现一次且不包含任何额外字符。以实例说明解题思路及实现过程。

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

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

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

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

» Solve this problem


这题,我没有什么好的做法。

采取的是最笨的方法:枚举。

具体做法:

在S串中枚举一个可能的Substring开始的位置然后进行验证。


class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> ans;

        if (L.size() == 0) {
            return ans;
        }
        
        int eL = L[0].size(), n = L.size();
        
        if (eL * n > S.size()) {
            return ans;
        }
        
        map<string, int> lists;
        for (vector<string>::iterator iter = L.begin(); iter != L.end(); iter++) {
            lists[*iter]++;
        }
        
        map<string, int> temp;
        string sub;
        for (int i = 0; i <= S.size() - n * eL; i++) {
            temp.clear();    
            temp.insert(lists.begin(), lists.end());
            
            int j = i, count = temp.size();
            while (true) {
                sub = S.substr(j, eL);
                int q = --temp[sub];
                if (q < 0) {
                    break;
                }
                if (q == 0) {
                    count--;
                    if (count == 0) {
                        ans.push_back(i);
                        break;
                    }
                }
                j += eL;
            }
        }
        
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值