#include<iostream>
#include <windows.h>
using namespace std;
/*
问题:求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计:
设计一个类 String,包括一个 len(字符串长度)和字符串指针 s。另有如下成员函数:
· void getstring() 从用户获取一个字符串。
· void display() 输出字符串。
· friend String maxsubstring(String str1,String str2) 友元函数,求两个字符串的最长
公共子串。
求两个字符串 s 和 t 的最长公共子串的算法思想如下:
*/
class Strings
{
int len;
char *p;
public:
void getstring(char s[]) //从用户获取一个字符串。
{
p = s;
}
void display() //输出字符串。
{
cout << p << endl;
}
friend void maxsubstring(Strings str1, Strings str2); //友元函数,求两个字符串的最长
};
void maxsubstring(Strings str1, Strings str2) //友元函数,求两个字符串的最长
{
int count[50] = {0};
int i = 0;
int k = 0;
int max = 0;
int m = 0;
char *ps[50] = { 0 };
for (char *pc1 = str1.p; *pc1 != '\0'; pc1++)
{
for (char *pc2 = str2.p; *pc2 != '\0'; pc2++)
{
char *temp1 = pc1;
char *temp2 = pc2;
if ((*temp1 == *temp2) && (*temp2 != '\0'))
{
ps[i] = temp1;//保留地址
while ((*temp1 == *temp2) && (*temp2 != '\0'))
{
temp1++;
temp2++;
count[i]++;
}
i++;
}
}
}
for (int i = 0; i < 50; i++)
{
//printf("%d\n", count[i]);
if (max < count[i])
{
k = i;
max = count[i];
}
}
printf("字符串子串最大长度:%d\n", max);
printf("该子串为:");
while (m < max)
{
printf(" %c ", *ps[k]);
ps[k]++;
m++;
}
}
int main()
{
char s1[50] = { 0 };
char s2[50] = { 0 };
cout << "输入第一个字符串:";
cin >> s1;
cout << "\n" << endl;
cout << "输入第二个字符串:";
cin >> s2;
cout << "\n" << endl;
Strings str1,str2;
str1.getstring(s1);
str2.getstring(s2);
//友元函数只是普通函数,可以在任意地方调用
maxsubstring(str1, str2);
system("pause");
}
#include <windows.h>
using namespace std;
/*
问题:求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计:
设计一个类 String,包括一个 len(字符串长度)和字符串指针 s。另有如下成员函数:
· void getstring() 从用户获取一个字符串。
· void display() 输出字符串。
· friend String maxsubstring(String str1,String str2) 友元函数,求两个字符串的最长
公共子串。
求两个字符串 s 和 t 的最长公共子串的算法思想如下:
*/
class Strings
{
int len;
char *p;
public:
void getstring(char s[]) //从用户获取一个字符串。
{
p = s;
}
void display() //输出字符串。
{
cout << p << endl;
}
friend void maxsubstring(Strings str1, Strings str2); //友元函数,求两个字符串的最长
};
void maxsubstring(Strings str1, Strings str2) //友元函数,求两个字符串的最长
{
int count[50] = {0};
int i = 0;
int k = 0;
int max = 0;
int m = 0;
char *ps[50] = { 0 };
for (char *pc1 = str1.p; *pc1 != '\0'; pc1++)
{
for (char *pc2 = str2.p; *pc2 != '\0'; pc2++)
{
char *temp1 = pc1;
char *temp2 = pc2;
if ((*temp1 == *temp2) && (*temp2 != '\0'))
{
ps[i] = temp1;//保留地址
while ((*temp1 == *temp2) && (*temp2 != '\0'))
{
temp1++;
temp2++;
count[i]++;
}
i++;
}
}
}
for (int i = 0; i < 50; i++)
{
//printf("%d\n", count[i]);
if (max < count[i])
{
k = i;
max = count[i];
}
}
printf("字符串子串最大长度:%d\n", max);
printf("该子串为:");
while (m < max)
{
printf(" %c ", *ps[k]);
ps[k]++;
m++;
}
}
int main()
{
char s1[50] = { 0 };
char s2[50] = { 0 };
cout << "输入第一个字符串:";
cin >> s1;
cout << "\n" << endl;
cout << "输入第二个字符串:";
cin >> s2;
cout << "\n" << endl;
Strings str1,str2;
str1.getstring(s1);
str2.getstring(s2);
//友元函数只是普通函数,可以在任意地方调用
maxsubstring(str1, str2);
system("pause");
}