VC算法题:给定一个目标串s,一个模式串t在s中出现多次,需要把多个t中间的字符打印出来
规定s字符串长度小于1000W,t字符串长度小于100W
例如:s=123456abckkkabc123456abcqwerty
t= abc;
打印:kkk123456
应用vc滑动窗口实现代码:
#ifndef STRINGQUERY_H_H
#define STRINGQUERY_H_H
#include <iostream>
#include <string>
using namespace std;
#define SUB_SIZE 100*10000
#define TARGET_SIZE 1000*10000
#define STRING_NULL ""
#define ERROR -1
static int j =0;
string StringQuery(string strTarget, string strSub)
{
/*应用滑动窗口机制*/
int nTargetPos = 0; // 目标串当前位置
int nSubPos = 0; // 模式串当前位置
const char *chTarget = strTarget.data(); // string转成char
const char *chSub = strSub.data(); // string转成char
while ( nTargetPos < strTarget.size())
{
if (chTarget[nTargetPos] == chSub[nSubPos])
{
nTargetPos++;
nSubPos++;
}
else
{
nTargetPos = nTargetPos-nSubPos+1;
nSubPos = 0;
}
if (nSubPos == strSub.size())
{
break;
}
}
if (strTarget.size() <= strSub.size())
{
return STRING_NULL;
}
/*递归*/
if (nSubPos == strSub.size())
{
return (++j > 1 ? strTarget.substr(0, nTargetPos-nSubPos) : STRING_NULL) + StringQuery(strTarget.substr(nTargetPos), strSub);
}
else
{
return STRING_NULL;
}
}
int main(void)
{
string strTarget;
string strSub;
if (strTarget.size() > TARGET_SIZE || strSub.size() > SUB_SIZE)
{
cout << "Please Check Target or Sub" << endl;
return ERROR;
}
cout << "Please Input Target String:" ;
getline(cin, strTarget);
cout << "Please Input Sub String:";
getline(cin, strSub);
cout << "OUTPUT:" << StringQuery(strTarget, strSub) << endl;
system("pause");
}
#endif //STRINGQUERY_H_H