Substring with Concatenation of All Words--LeetCode

题目:

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).

思路:很淳朴的思路,依据最基本的想法进行查找

虽说循环是三层循环,但最多是平方级别的复杂度

#include <iostream>
#include <string>
#include <vector>
 
using namespace std;
/*
 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).
*/



void Concatenation(vector<string>& vec,string& s,vector<int>& indices)  
{
	int num = vec.size(); // 匹配数组的数目 
	int len = s.size(); // 字符串的长度 
	int sublen = vec[0].size(); //每一个被匹配的字符串的长度
	
	vector<int> flag(vec.size(),0);
	int count;
	int i,j,k;
	for(i=0;i<len-num*sublen;i++)
	{
		count = 0;
		flag.assign(flag.size(),0);
		for(j=i;j<len;j++)
		{
			for(k=0;k<num;k++)
				if(count < num && !s.compare(j,sublen,vec[k]))
				{	
					if(flag[k] == 1)
					{
						i = j-1;
						j = len;
						break;
					}
					else
					{
						flag[k] =1;
						count++; 
						if(count == num)
						{
							indices.push_back(j-(num-1)*sublen);
							i = j-1;
							j = len;									
						}
						j+=sublen-1;
						break;
					}
				}
		}	 
	} 
}
int main()  
{
	string s("sbarfoothefoobarman");
	string s1("foo");
	string s2("bar");
	vector<string> vec;
	vec.push_back(s1);
	vec.push_back(s2);
	vector<int> indices; 	
 	
	Concatenation(vec,s,indices);
	
	for(int i=0;i<indices.size();i++)
		cout<<indices[i]<<endl;
	return 0;	
}
ps:其实,感觉这道题的思路还可以是别的,比如说我们知道么每个字符串的长度都知道,那么我们从头开始遍历S串,如果发现某一个字母和L中某一个单词的首字母相同,那么就进行匹配,如果匹配成功,看下一个连续的能否被匹配,记录字符串可以使用hash,也可以使用set,一旦开始匹配,知道最后所有的单词都被匹配之后才会终结!!!
 这个题目还有别的思路,比如讲带查找的字符串存储到set或者map中,然后在整个字符串中进行查找,因为每个字符串的长度已经规定,所以对于字符串中的去子串的长度是一定的,这样讲当与在map或者set中查找,这样总的时间复杂度是O(n*logn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值