Find the longest common sub-sequence

Description:

Given 3 strings of all having length < 100,the task is to find the longest common sub-sequence
in all three given sequences.

Example:

Input : str1 = "geeks"
str2 = "geeksfor"
str3 = "geeksforgeeks"
Output : 5
Longest common subsequence is "geeks"
i.e., length = 5
Input : str1 = "abcd1e2"
str2 = "bc12ea"
str3 = "bd1ea"
Output : 3
Longest common subsequence is "b1e"
i.e. length = 3.

解题方法:

在两个string中寻找LCS:
假设string1的长度为m,string2的长度为n。
则我们创建一个m+1 * n+1的矩阵,矩阵DP[i][j]代表的是,当取string1前i个字符和取string2前j个字符时,它们的LCS长度为多少。
则状态转移方程为:

  1. 当string1[i - 1] == string2[j - 1], 则DP[i][j] = DP[i - 1][j - 1] + 1;这代表着当我们从string1和string2再各自取出一个字符,并且这两个字符相同,这两个substring的LCS的长+=1
  2. 否则,DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]);

这道题是寻找两个string的LCS的升级版。
状态转移方程为:

  1. 当string1[x - 1] == string2[y - 1] == string3[z - 1], 则DP[x][y][z] = DP[x - 1][y - 1][z - 1] + 1;
  2. 否则,DP[x][y][z] = max(DP[x - 1][y][z], DP[x][y - 1][z], DP[x][y][z - 1]);

Time Complexity:

O(n^3)

完整代码:

int longestSubSequence(string& str1, string& str2, string& str3) {
    int size1 = str1.size(), size2 = str2.size(), size3 = str3.size();
    vector>> DP(size1 + 1, vector>(size2 + 1, vector(size3 + 1, 0)));
    for(int x = 1; x <= size1; x++) {
        for(int y = 1; y <= size2; y++) {
            for(int z = 1; z <= size3; z++) {
                if(str1[x - 1] == str2[y - 1] && str2[y - 1] == str3[z - 1]) {
                    cout<

你可能感兴趣的:(Find the longest common sub-sequence)