LeetCode 30. Substring with Concatenation of All Words

30. Substring with Concatenation of All Words

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

Approach

题目大意:从一组字符串中找到连续一串与words所有字符串组合相同
解题思路:使用滑动窗口的思想,设words中单词长为len,我们就可以从字符串s的0~len出发(为什么只用从0~len出发呢,因为words的每个单词长度是确定的,这样其实从字符串0~len出发每次递增len长度,你会发现全都会访问到。),每次递增单词长度就为len,窗口大小维护为words的大小,这样当不连续的时候,就消减窗口,直到连续为止,这样当窗口大小又等于words的大小的时候就可以把头放入vector中。

Code

class Solution {
public:
    vector<int> findSubstring(string s, vector<string> &words) {
        if (s.empty() || words.empty())
            return vector<int>();
        vector<int> ans;
        int m = words[0].size(), n = s.size(), sum = words.size(), nn = n - m;
        unordered_map<string, int> count;
        for (const string &w:words)count[w]++;
        for (int i = 0; i < m; i++) {
            unordered_map<string, int> mp;
            int left = i, cnt = 0;
            for (int j = i; j <= nn; j+=m) {
                string tmp = s.substr(j, m);
                if (!count.count(tmp)) {
                    cnt = 0;
                    left = j+m;
                    mp.clear();
                    continue;
                }
                mp[tmp]++;
                if (mp[tmp] <= count[tmp])cnt++;
                else {
                    while (mp[tmp] > count[tmp]) {
                        string stmp = s.substr(left, m);
                        mp[stmp]--;
                        left += m;
                        cnt--;
                    }
                
                    cnt++;
                }
                if (cnt == sum) {
                    ans.push_back(left);
                }
            }
        }
        return ans;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值