이 튜토리얼에서는 가장 긴 commonsubstring을 출력하는 프로그램에 대해 논의할 것입니다.
이를 위해 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