C++入门程序:求两个字符串的最长公共字串。c++新手求解。解决思路
C++入门程序:求两个字符串的最长公共字串。c++新手求解。
题目: 类和对象的编程
求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计一个类String,包括一个len(字符串长度)和字符串指针s。另有如下成员函数
void getstring ( ) 从用户获取一个字符串
void display ( ) 输出字符串。
举例:
输入字符串s1:this is a string
输入字符串s2:my string is abc
s1 和s2最长公共子字符串=string(长度为7)
这是我们英明的C++老师给我们还没学习一章C++课程的学生出的题,真的对她很无语了,完全不了解我们到底掌握了几多。
希望得到大神的指导,强调点我们用的编译器是vc6.0。真心求解,我已经做了一晚上了,还是毫无进展。
------解决方案--------------------
下面的代码 直接运行:
题目: 类和对象的编程
求两个字符串的最长公共子串。
要求:输入两个字符串,输出它们的最长公共子串,包括长度。
设计一个类String,包括一个len(字符串长度)和字符串指针s。另有如下成员函数
void getstring ( ) 从用户获取一个字符串
void display ( ) 输出字符串。
举例:
输入字符串s1:this is a string
输入字符串s2:my string is abc
s1 和s2最长公共子字符串=string(长度为7)
这是我们英明的C++老师给我们还没学习一章C++课程的学生出的题,真的对她很无语了,完全不了解我们到底掌握了几多。
希望得到大神的指导,强调点我们用的编译器是vc6.0。真心求解,我已经做了一晚上了,还是毫无进展。
------解决方案--------------------
下面的代码 直接运行:
- C/C++ code
#include <iostream> using std::cin; using std::cout; using std::endl; class string { public: string(); ~string(); void getstring(); void display(); int len; char *s; }; string::string():len(0),s(NULL) {} string::~string() { if(s) delete []s; s = NULL; } void string::getstring() { s = new char[200]; gets(s); len = strlen(s); } void string::display() { cout << s; } int main() { string s1,s2; cout << "please input character s1:" << endl; s1.getstring(); cout << "please input character s2:" << endl; s2.getstring(); int i=0, j = 0,m,k,maxp = 0,maxlen = 0,count,q; while(s2.s[i] && i < s2.len) { j = i; while(s2.s[j] && s2.s[j] != ' ') ++j; for(m = 0; s1.s[m];++m) { k = i; if(s1.s[m] == s2.s[k]) { q = m; count = 0; while(k != j && s1.s[q] == s2.s[k]) {++q; ++k; ++count; } if(k == j) { if(count > maxlen) { maxlen = count; maxp = m; } break; } } } i = j + 1; } cout << endl << endl <<"s1= "; s1.display(); cout << endl << "s2= "; s2.display(); cout << endl; if(maxlen != 0) {cout << "s1和s2的最长公共字符子串="; for(i = maxp;i < maxp + maxlen;++i) cout << s1.s[i]; cout << endl; } else { cout <<"s1和s2没有公共字符子串!" << endl; } }