用了两个方法吧,第一种直接用strstr函数,很简单,第二种,用了kmp,比较麻烦。
#include<iostream>
#include<string.h>
using namespace std;
void revert(char []);
int main()
{
char s[350] = {},s1[30] = {},s2[30] = {};
cin.getline(s,330,',');
cin.getline(s1,25,',');
cin.getline(s2,25);
int a,b;
if (strstr(s,s1) == 0)
a = -1;
else
a = strstr(s,s1) - s + strlen(s1);
revert(s);//将s和s2翻转,这样就可以用strstr函数找到倒数第一个s2的位置。
revert(s2);
if (strstr(s,s2) == 0)
b = -1;
else
b = strlen(s) - (strstr(s,s2) - s) - strlen(s2);
if (a == -1 || b == -1)
cout<<-1;
else if (b - a >= 0)
cout<<b - a;
else
cout<< -1;
return 0;
}
void revert( char t[])
{
int i = 0 ;
int l = strlen(t);
for (i = 0 ; i < l/2 ; i ++)
{
t[i] = t[l - i - 1] ^ t[i];
t[l - i - 1] = t[l - i - 1] ^ t[i];
t[i] = t[l - i - 1] ^ t[i];
}
}
#include<iostream>
#include<cmath>
#include"string.h"
using namespace std;
void findnext(int next[], char p[]);
int findpos(char t[], char p[]);
int main()
{
char s[350] =
{ }, s1[30] =
{ }, s2[30] =
{ };
cin.getline(s, 310, ',');
cin.getline(s1, 30, ',');
cin.getline(s2, 30);
int a, b, t = -1;
a = findpos(s, s1);
//这种方法没有采用倒转的方法,而是每次都寻找一次,没找到一次s2,就把s2的第一个字符置为','(因为题目中告诉我们字符串不含有',',所以可以放心的将其置为',',这样就可以保证不会给s1中多增加一个目标字符串s2,而且不会忽略掉每一个s2)
do
{
b = t;
t = findpos(s,s2);
s[t] = ',';
}while (t != -1);
if (a == -1 || b == -1)
cout << -1;
else if (b - a - (int)strlen(s1) >= 0)
cout << b - a - (int)strlen(s1);
else
cout<< -1;
return 0;
}
int findpos(char t[], char p[])
{
int next[30] =
{ };
next[0] = -1;
int i = 0;
int j = 0;
findnext(next, p);
int l = strlen(p);
int l2 = strlen(t);
while (j < l && i < l2)
{
if (p[j] == t[i] || j == -1)
{
j++;
i++;
}
else
{
j = next[j];
}
}
if (p[j] == 0)
{
return i - strlen(p);
}
else
return -1;
}
void findnext(int next[], char p[])
{
next[0] = -1;
int i, j;
i = 0;
j = -1;
int lp = strlen(p);
while (i < lp - 1)
{
while (j >= 0 && p[i] != p[j])
j = next[j];
j++;
i++;
next[i] = j;
}
}