使用 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