//传统的字符串比较算法
#include <stdio.h>
#include <string.h>
char s[51],t[11];
int next[11];
int index(char *s,char *t,int pos)
{
int i = pos;
int j = 0;
int len1 = strlen(s);
int len2 = strlen(t);
while(i<len1&&j<len2)
{
if(s[i]==t[j])
{
i++;
j++;
}
else //指针回溯
{
i=i-j+1;
j=0;
}
}
if(j>=len2)
return i-len2;
}
int main()
{
int pos;
gets(s);
gets(t);
scanf(“%d”,&pos);
int no = index(s,t,pos);
if(no>0)
printf(“String s contains a substring t~~~\n”);
else
printf(“String s doesn’t contain a substring t~~~\n”);
return 0;
}
//改进后的字符串比较算法
#include <stdio.h>
#include <string.h>
char s[51],t[11];
int next[11];
void get_next(char* t,int next[])
{
int i = 1;
int j = 0;
next[0] = -1;
while(i<strlen(t))
{
if(j==-1||t[i]==t[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int index(char *s,char *t,int pos)
{
int i = pos;
int j = 0;
int len1 = strlen(s);
int len2 = strlen(t);
while(i<len1&&j<len2)
{
if(j==-1||s[i]==t[j])//第一个字符都不匹配或者字符相等的情况
{
i++;
j++;
}
else //i指针不回溯,j指针
{
//i=i-j+1;
j=next[j];
}
}
if(j>=len2)
return i-len2;
else
return -1;
}
int main()
{
int pos;
gets(s);
gets(t);
scanf(“%d”,&pos);
get_next(t,next);
int no = index(s,t,pos);
if(no>0)
printf(“String s contains a substring t~~~\n”);
else
printf(“String s doesn’t contain a substring t~~~\n”);
return 0;
}
//再次改进后的字符串比较算法
#include <stdio.h>
#include <string.h>
char s[51],t[11];
int next[11];
void get_nextval(char* t,int next[])
{
int i = 1;
int j = 0;
next[0] = -1;
while(i<strlen(t))
{
if(j==-1||t[i]==t[j])
{
i++;
j++;
if(t[i]!=t[j])
next[i] = j;
else
next[i] = next[j];
}
else
{
j = next[j];
}
}
}
int index(char *s,char *t,int pos)
{
int i = pos;
int j = 0;
int len1 = strlen(s);
int len2 = strlen(t);
while(i<len1&&j<len2)
{
if(j==-1||s[i]==t[j])//第一个字符都不匹配或者字符相等的情况
{
i++;
j++;
}
else //i指针不回溯,j指针
{
//i=i-j+1;
j=next[j];
}
}
if(j>=len2)
return i-len2;
else
return -1;
}
int main()
{
int pos;
gets(s);
gets(t);
scanf(“%d”,&pos);
get_nextval(t,next);
int no = index(s,t,pos);
if(no>0)
printf(“String s contains a substring t~~~\n”);
else
printf(“String s doesn’t contain a substring t~~~\n”);
return 0;
}