Given a a list of words,L,that are all of the same length,and a string, S,Find the starting postion of substring of S that is a concatenation of each word in words exactly once and without any intervening characters.
输入:第一行 L一组单词,中间用空格分开,单词的个数为1-100个,每个单词不超过10个字母
第二行 S一个字符串
输出:包含完整单词的序列字串的开始索引
#include <iostream>
#include<string>
#include<vector>
using namespace std;
bool Issubstring(string s, vector<string> L, int Length, int count);
int main() {
//string L[2] = { "abc","def" };
//string S= "wsxabcdefqwe";
int Word_count=0;
int Word_length = 0;
string L0="";
getline(cin, L0);
string S;
cin >> S;
while (L0[Word_length] != ' ')
Word_length++;
for (int i = 0; i < L0.length(); i++) {
if (L0[i] ==' ')
Word_count++;
}
Word_count++;
vector<string> L(Word_count);
for (int i = 0, k=0; i < L0.length(); i=i+Word_length+1,k++) {
L[k] = L0.substr(i, Word_length);
}
/*for (int i = 0; i < Word_count; i++) {
cout << L[i] << endl;
}*/
for (int i = 0; i < S.length(); i++) {
string tmp = S.substr(i, Word_length*Word_count);
//cout << tmp << endl;
if (Issubstring(tmp, L, Word_length, Word_count)) {
cout << i;
}
}
return 0;
}
bool Issubstring(string s, vector<string> L, int Length, int count) {
vector<string> word(count);
vector<int> flag(count);
for (int i = 0, j = 0; i < s.length(); i += Length,j++) {
word[j] = s.substr(i, Length);
//cout << word[j] << endl;
}
for (int i = 0; i < count; i++) {
for (int k = 0; k < count; k++)
{
if (L[i] == word[k]) {
flag[i] = 1;
}
}
}
for (int i = 0; i < count; i++) {
if (flag[i]== 0)
{
return false;
}
}
return true;
}
如上所示,主要的思想是一个固定大小的窗口,并且不断地向右滑动,窗口内对单词进行分隔,循环比较,如果所有的标志位均为1,说明该组单词均在这个子串中,否则继续 向右滑动,因为题中说是唯一的,可在找到以后加入break语句终止循环,亦或者是字串的长度小于所有单词长度之和。另外,我写的这个程序输入必须严格按照题中要求,没有对输入加以限制,任意的输入可能导致程序不能正常运行。