Philip Harrell
Profilo di
Nome | Philip Harrell |
---|---|
Indirizzo email | crummyreeve@gmail.com |
Avatar | |
Messaggi | 1 |
-
- 2024-10-25 05:22:00
- Re: Problem with Longest Common Substring
- Forum >> Programmazione Python >> Web e Reti
-
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// Function to find the Longest Common Substring
string LCS(string X, string Y) {
// Find lengths of given strings
int m = X.length();
int n = Y.length();
// Declare the 2D array to store lengths of longest common suffixes
vector<vector<int>> L(m + 1, vector<int>(n + 1, 0));
// Variable to keep track of the maximum length of LCS
int maxLength = 0;
int endIdx = 0; // To store the end index of the longest common substring in X
// Fill the array with values
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i - 1] == Y[j - 1]) {
Lj = L[i - 1][j - 1] + 1;
// Update maxLength if a longer common substring is found
if (Lj > maxLength) {
maxLength = Lj;
endIdx = i - 1;
}
} else {
Lj = 0;
}
}
}
// If there is no common substring, return an empty string
if (maxLength == 0) {
return "";
}
// Extract the longest common substring
return X.substr(endIdx - maxLength + 1, maxLength);
}
int main() {
string X = "ABABC";
string Y = "BABC";
cout << "Longest Common Substring: " << LCS(X, Y) << endl;
return 0;
}
Initialization ofL : Used a vector of vectors to declare a 2D array with zero-initialized values to store lengths of common substrings at each point.Array Access Errors : Fixed the syntax and index accesses, ensuring Ljit was updated correctly.Tracking Max Length and End Index : Added variables maxLengthand endIdxto keep track of the longest common substring's length and where it ends.Return Statement : Used substrto return the longest substring based on the endIdxand maxLength.