Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc a 123456 45 abc ddd
Example Output
1 4 -1
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000010
#define SUM 30
#define ERROR -1
#define ok 1
int next[1000010];
typedef struct
{
char *ch;
int len;
int size;
} String;
void InitString(String &S); //串初始化
void CleanString(String &S); //清空串
int Strlen(char s[]); //返回串长度
void Display(String &S); //输出串
void StrCopy(String &S1, char s[]); //将串s2复制到s1中
void GetNext(String &S);
int IndexKmp(String &S1, String &S2);
int main()
{
String S1, S2;
InitString(S1);
while(~scanf("%s", S1.ch))
{
InitString(S2);
scanf("%s", S2.ch);
GetNext(S2);
int flag = IndexKmp(S1, S2);
if(flag)
printf("%d\n", flag);
else
printf("-1\n");
CleanString(S1);
CleanString(S2);
InitString(S1);
}
return 0;
}
void InitString(String &S) //串初始化
{
S.ch = (char *)malloc(MAXSIZE * sizeof(char));
S.len = 0;
S.size = MAXSIZE;
}
void CleanString(String &S) //清空串
{
if(S.ch)
{
free(S.ch);
S.ch = NULL;
}
S.len = 0;
S.size = 0;
}
int Strlen(char s[]) //返回串长度
{
int i = 0;
while(s[i] != '\0')
i++;
return i;
}
void Display(String &S) //输出串
{
int i;
for(i = 0; i < S.len; i++)
printf("%c", S.ch[i]);
printf("\n");
}
void StrCopy(String &S1, char s[]) //将串s2复制到s1中
{
CleanString(S1);
int n = Strlen(s);
S1.ch = (char *)malloc((n + 1) * sizeof(char));
S1.len = n;
S1.size = n + 1;
int i;
for(i = 0; i < n; i++)
S1.ch[i] = s[i];
}
void GetNext(String &S)
{
int n = Strlen(S.ch);
int i = 1;
next[1] = 0;
int j = 0;
while(i < n)
{
if(j == 0 || S.ch[i] == S.ch[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int IndexKmp(String &S1, String &S2)
{
int i = 0;
int j = 0;
int n = Strlen(S1.ch);
int m = Strlen(S2.ch);
while(i < n && j < m)
{
if(j == 0 || S1.ch[i] == S2.ch[j])
{
i++;
j++;
}
else
j = next[j];
}
if(j >= m)
return i - m + 1;
else
return 0;
}
#include <stdio.h>
#include <string.h>
int next[1000005];
void getnext(char s[])
{
int i=0,j=-1;
next[0]=-1;
int n=strlen(s);
while(i<n)
{
if(j==-1||s[i]==s[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp(char s1[],char s2[])
{
int i=0,j=0;
int n1=strlen(s1),n2=strlen(s2);
while(i<n1&&j<n2)
{
if(j==-1||s1[i]==s2[j])
{
i++;j++;
}
else
j=next[j];
}
if(j>=n2) printf("%d\n",i-n2+1);
else
printf("-1\n");
}
int main()
{
char s1[1000005],s2[1000005];
while(gets(s1))
{
gets(s2);
getnext(s2);
kmp(s1,s2);
}
}