题目:
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)