Facebook 2006 试题

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语句终止循环,亦或者是字串的长度小于所有单词长度之和。另外,我写的这个程序输入必须严格按照题中要求,没有对输入加以限制,任意的输入可能导致程序不能正常运行。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值