采用顺序结构存储串,设计实现求串S和串T的一个最长公共子串的算法。
源代码
/**********
date:2021-10-31
author:sy
version:1.0
Description:采用顺序结构存储串,设计实现求串S和串T的一个最长公共子串的算法
************/
#include<stdio.h>
#include<string.h>
/*定义顺序结构*/
typedef struct SeqString {
char ch[100];
int x=0;
int length;
}SeqStack;
int main()
{
char astr[100], bstr[100];
printf("请输入字符串S:");
gets(astr); //gets(str) 约等于 scanf("%s",&str) 会把读到的字符串写入数组,但又不同。
printf("请输入字符串T:"); // scanf("%s",&str) :读到空格便停止。
gets(bstr); //gets(str) :一直读到敲回车(不管中间是否有空格)。
int max = 0;
int i, j;
int alen = strlen(astr);
int blen = strlen(bstr);
SeqStack stack[100];
int n = 0;
int MAXstring=0;
for (i = 0; i < alen; i++) //遍历第一个字符串
{
for (j = 0; j < blen; j++) //遍历第二个字符串
{
if (astr[i + j] == bstr[j])
{
max++;
stack[n].ch[stack[n].x] = bstr[j];
stack[n].x++;
}
else
{
stack[n].ch[stack[n].x] = '\0';
stack[n].length = max;
if (max > MAXstring)
MAXstring = max;
max = 0;
n ++;
}
}
}
printf("最长公共子串长度为%d\n", MAXstring);
printf("最长公共子串为:",MAXstring);
for (int k = 0; k < n; k++)
{
if (stack[k].length == MAXstring)
puts(stack[k].ch); // puts()在输出字符串时会将’\0’自动转换成’\n’进行输出,
// 也就是说,puts方法输出完字符串后会自动换行。
}
return 0;
}
运行结果