数据结构实验之串二:字符串匹配
Time Limit: 1000MS Memory limit: 65536K
题目描述
给定两个字符串string1和string2,判断string2是否为string1的子串。
输入
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)
输出
对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。
示例输入
abc a 123456 45 abc ddd
示例输出
YES YES NO
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void index(char s1[], char s2[])
{
int i=0,j=0;
while(s1[i+j]!='\0'&&s2[j]!='\0')
{
if(s1[i+j]==s2[j])
j++; //继续比较后继字符
else
{
i++;
j=0;
}//i后移,重新开始新一轮比较
}
if(s2[j]=='\0') //匹配成功
printf("YES\n");
else //不存在和串t相同的子串
printf("NO\n");
}
int main()
{
char s1[101], s2[101];
while(gets(s1)!=NULL)
{
gets(s2);
index(s1, s2);
}
}
标准格式
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef char status;
typedef struct
{
char *ch; //若是非空串,按串长分配存储区, 否则ch为NULL
int length; //串长度
} String;
status initstring(String &s)//初始化一个串
{
s.ch = (char *)malloc(sizeof(char));
if(!s.ch) exit(0);
s.ch=NULL;
s.length = 0;
return 1;
}
void strassign(String &s, char str[])//为串t赋值
{
if(s.ch)
free(s.ch); //释放t原有空间
int i=0;
while(str[i]!='\0') //求str长度i
i++;
if(!i)
{
s.ch = NULL;
s.length = 0;
}
else
{
s.ch = (char *) malloc ((i+1) * sizeof(char));
if(!s.ch) exit(0);
int j=0;
for(j=0; j<i; j++)
s.ch[j]=str[j];
s.length = i;
}
}
status concat(String &t, String &s1, String &s2)
{
int i, j;
if(t.ch)
free(t.ch);
t.ch = (char *) malloc ((s1.length+s2.length+1) * sizeof(char));
if(!t.ch) exit(0);
for(i=0; i<s1.length; i++)
t.ch[i] = s1.ch[i];
t.length=s1.length+s2.length;
for(i=0; i<s2.length; i++)
t.ch[s1.length+i]=s2.ch[i];
return 1;
}
int strlength(String &s)
{
return s.length;
}
int index(String &s, String &t, int pos)// T为非空串。若主串S中第 pos 个字符之后存在与t相等的子串,
// 则返回第一个这样的子串在S中的 位置,否则返回0
{
if(pos>0)
{
int i=pos-1;
int j=0;
int tlen = strlength(t);
int slen = strlength(s);
for(j=0; j<tlen; j++)
{
if(s.ch[i+j]!=t.ch[j])
{
i++;
j=-1;
}//i后移,重新开始新一轮比较
if(i+j>=slen)
{
break;
}
}
if(j==tlen) //匹配成功
return (i+1);
else //不存在和串t相同的子串
return -1;
}
return -1; // 位置不合法,s中不存在与t相等的子串
}
int main()
{
char str1[111], str2[111];
String s1, s2, t;
while(~scanf("%s", str1))
{
initstring(s1);
initstring(s2);
strassign(s1, str1);
scanf("%s", str2);
strassign(s2, str2);
int e = index(s1, s2, 1);
if(e!=-1) printf("YES\n");
else printf("NO\n");
}
}
本文介绍了一个简单的字符串匹配算法实现,通过示例展示了如何判断一个字符串是否为另一个字符串的子串。提供了两种不同的实现方式,包括直接字符比较和使用数据结构进行处理的方法。
2896

被折叠的 条评论
为什么被折叠?



