1. 程式人生 > >常見演算法問題之最長公共子串問題(Longest common substring problem)

常見演算法問題之最長公共子串問題(Longest common substring problem)

對於尋找兩個字串的最長公共子字串的問題,暴力搜尋的方式的時間複雜度將高達O(n^3), 而通過字尾樹的方式可將時間複雜度降低到O(n^2)。

以下是我實現的C++原始碼:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution
{
public:
    int FindLongestCommonSubstring(string str1, string str2, vector<string>& MaxSubstr)
    {
        int
m = str1.length(), n = str2.length(), i, j, k = 0, MaxSubstrLen = 0; vector<vector<int>> L(m, vector<int>(n, 0)); // L記錄相同子串的長度 for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (str1[i] == str2[j]) { if
(i == 0 || j == 0) L[i][j] = 1; else L[i][j] = L[i - 1][j - 1] + 1; if (MaxSubstrLen < L[i][j]) { MaxSubstrLen = L[i][j]; k = 0; MaxSubstr[k] = str1.substr(i + 1
- MaxSubstrLen, MaxSubstrLen); } else if (MaxSubstrLen == L[i][j] && MaxSubstr[k] != str1.substr(i + 1 - MaxSubstrLen, MaxSubstrLen)) //有多個長度相同的MaxSubstr, 且要排除多個MaxSubstr內容相同的情況,如當str1="a", str2="aaaa" MaxSubstr[++k] = str1.substr(i + 1 - MaxSubstrLen, MaxSubstrLen); } else L[i][j] = 0; } } return k; } }; int main() { string str1 = "aaabaaaeabcd"; string str2 = "bbbababcde"; vector<string> MaxSubstr(str1.length()); //MaxSubstr個數不會超過str1和str2的長度,這裡取str1.length Solution a; int MaxSubstrNum = a.FindLongestCommonSubstring(str1, str2, MaxSubstr); for (int i = 0; i <= MaxSubstrNum; i++) cout << MaxSubstr[i] << ' '; cout << endl; return 0; }