使用 C++ 打印最长公共子串的程序
在本教程中,我们将讨论如何编写程序来打印最长的公共子串。
为此,我们将给定两个字符串,比如 A 和 B。我们必须打印输入字符串 A 和 B 的最长公共子串。
例如,如果我们给定“HelloWorld”和“world book”。在这种情况下,最长的公共子串将是“world”。
示例
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void print_lstring(char* X, char* Y, int m, int n){
int longest[m + 1][n + 1];
int len = 0;
int row, col;
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
longest[i][j] = 0;
else if (X[i - 1] == Y[j - 1]) {
longest[i][j] = longest[i - 1][j - 1] + 1;
if (len < longest[i][j]) {
len = longest[i][j];
row = i;
col = j;
}
}
else
longest[i][j] = 0;
}
}
if (len == 0) {
cout << "There exists no common substring";
return;
}
char* final_str = (char*)malloc((len + 1) * sizeof(char));
while (longest[row][col] != 0) {
final_str[--len] = X[row - 1];
row--;
col--;
}
cout << final_str;
}
int main(){
char X[] = "helloworld";
char Y[] = "worldbook";
int m = strlen(X);
int n = strlen(Y);
print_lstring(X, Y, m, n);
return 0;
}输出
world
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP