Substring with Concatenation of All Words

本文介绍了一种用于查找字符串S中所有由单词列表L拼接而成的子串的起始索引的方法。通过滑动窗口技术和映射表进行高效匹配与计数,确保每个单词恰好使用一次且不包含额外字符。

摘要生成于 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).

 

1.size()的返回值时unsigned int,计算式会溢出,所以有size的减法一定要转换成int

2.滑动窗口,提升速度

   s="abcdaxx" L={"a","b","c","d","e"}

   [a]bcdaxx --->  [ab]cdaxx --->[abc]daxx --->[abcd]axx

   若a已经出现过切窗口中出现次数==L中的出现次数,则向后滑 a【bcda】xx

  若为当前到x的情况,则i+1

 

 

class Solution {
public:
	map<string, int> count;
	map<string, int> use;
	map<string, int> index;




    vector<int> findSubstring(string S, vector<string> &L) 
	{
		vector<int> rtv;
		if(S.size() == 0 || L.size()== 0 || S.size() < L[0].size())return rtv;
		int found_count ;
		int flag = 0;
		int len = L[0].size(),lsize = L.size(),ssize = S.size();

		for(int j = 0; j < L.size(); ++j)
					count[L[j]]++;
		int x = 0;
		for(int i = 0; i <= ssize - len * lsize; )
		{
			x++;
			use.clear();
			index.clear();
			flag = 0;
			found_count = 0;
			string s = S.substr(i, len);
			

			while(count.find(s) != count.end())
			{	
				use[s]++;
				if(use[s] > count[s])break;

				if(index.find(s) == index.end())index[s] = i + found_count * len;

				++found_count;
				if(found_count == lsize)
				{
					flag = 1;
					break;
				}

				s = S.substr(i + found_count * len, len);
			}
			
			if(flag)
			{
				rtv.push_back(i);
				i++;
				continue;
			}
			
			if(index.find(s) != index.end() && use.find(s) != use.end() && use[s] > count[s])
			{
				i = index[s] + len;
				continue;
				
				
			}
			
			
			i++;

		}
		return rtv;
    }
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值