LCS formado por segmentos consecutivos de al menos longitud K

Dadas dos strings s1, s2 y K, encuentre la longitud de la subsecuencia más larga formada por segmentos consecutivos de al menos longitud K.
Ejemplos: 
 

Input : s1 = aggayxysdfa
        s2 = aggajxaaasdfa 
         k = 4
Output : 8 
Explanation: aggasdfa is the longest
subsequence that can be formed by taking
consecutive segments, minimum of length 4.
Here segments are "agga" and "sdfa" which 
are of length 4 which is included in making 
the longest subsequence. 

Input : s1 = aggasdfa 
        s2 = aggajasdfaxy
         k = 5
Output : 5 

Input: s1 = "aabcaaaa" 
       s2 = "baaabcd"  
        k = 3
Output: 4 
Explanation: "aabc" is the longest subsequence that 
is formed by taking segment of minimum length 3. 
The segment is of length 4. 

Requisito previo : Subsecuencia común más larga 
Cree una array LCS[][] donde LCS i, j denota la longitud de la subsecuencia común más larga formada por caracteres de s1 hasta i y s2 hasta j que tengan segmentos consecutivos de al menos una longitud K. Cree un cnt[ ][] array para contar la longitud del segmento común. cnt i, j = cnt i-1, j-1 +1 cuando s1[i-1]==s2[j-1]. Si los caracteres no son iguales, los segmentos no son iguales, por lo tanto, marque cnt i, j como 0. 
Cuando cnt i, j >=k , actualice el valor de lcs agregando el valor de lcs i-a, ja donde a es la longitud de los segmentos a<=cnt i, j. La respuesta para la subsecuencia más larga con segmentos consecutivos de al menos una longitud k se almacenará en lcs[n][m] donde n y m son la longitud de string1 y string2. 
 

C++

// CPP program to find the Length of Longest
// subsequence formed by consecutive segments
// of at least length K
#include <bits/stdc++.h>
using namespace std;
 
// Returns the length of the longest common subsequence
// with a minimum of length of K consecutive segments
int longestSubsequenceCommonSegment(int k, string s1,
                                           string s2)
{
    // length of strings
    int n = s1.length();
    int m = s2.length();
 
    // declare the lcs and cnt array
    int lcs[n + 1][m + 1];
    int cnt[n + 1][m + 1];
 
    // initialize the lcs and cnt array to 0
    memset(lcs, 0, sizeof(lcs));
    memset(cnt, 0, sizeof(cnt));
 
    // iterate from i=1 to n and j=1 to j=m
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
 
            // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
            lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]);
 
            // when both the characters are equal
            // of s1 and s2
            if (s1[i - 1] == s2[j - 1])
                cnt[i][j] = cnt[i - 1][j - 1] + 1;
 
            // when length of common segment is
            // more than k, then update lcs answer
            // by adding that segment to the answer
            if (cnt[i][j] >= k) {
 
                // formulate for all length of segments
                // to get the longest subsequence with
                // consecutive Common Segment of length
                // of min k length
                for (int a = k; a <= cnt[i][j]; a++)
 
                    // update lcs value by adding segment length
                    lcs[i][j] = max(lcs[i][j],
                                    lcs[i - a][j - a] + a);
                 
            }
        }
    }
 
    return lcs[n][m];
}
 
// driver code to check the above function
int main()
{
    int k = 4;
    string s1 = "aggasdfa";
    string s2 = "aggajasdfa";
    cout << longestSubsequenceCommonSegment(k, s1, s2);
    return 0;
}

Java

// Java program to find the Length of Longest
// subsequence formed by consecutive segments
// of at least length K
 
class GFG {
 
    // Returns the length of the longest common subsequence
    // with a minimum of length of K consecutive segments
    static int longestSubsequenceCommonSegment(int k, String s1,
                                               String s2)
    {
        // length of strings
        int n = s1.length();
        int m = s2.length();
     
        // declare the lcs and cnt array
        int lcs[][] = new int[n + 1][m + 1];
        int cnt[][] = new int[n + 1][m + 1];
     
     
        // iterate from i=1 to n and j=1 to j=m
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
     
                // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
                lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
     
                // when both the characters are equal
                // of s1 and s2
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    cnt[i][j] = cnt[i - 1][j - 1] + 1;
     
                // when length of common segment is
                // more than k, then update lcs answer
                // by adding that segment to the answer
                if (cnt[i][j] >= k)
                {
     
                    // formulate for all length of segments
                    // to get the longest subsequence with
                    // consecutive Common Segment of length
                    // of min k length
                    for (int a = k; a <= cnt[i][j]; a++)
     
                        // update lcs value by adding
                        // segment length
                        lcs[i][j] = Math.max(lcs[i][j],
                                        lcs[i - a][j - a] + a);
                     
                }
            }
        }
     
        return lcs[n][m];
    }
     
    // driver code to check the above function
    public static void main(String[] args)
    {
        int k = 4;
        String s1 = "aggasdfa";
        String s2 = "aggajasdfa";
        System.out.println(longestSubsequenceCommonSegment(k, s1, s2));
    }
}
 
// This code is contributed by prerna saini.

Python3

# Python3 program to find the Length of Longest
# subsequence formed by consecutive segments
# of at least length K
 
# Returns the length of the longest common subsequence
# with a minimum of length of K consecutive segments
def longestSubsequenceCommonSegment(k, s1, s2) :
     
    # length of strings
    n = len(s1)
    m = len(s2)
 
    # declare the lcs and cnt array
    lcs = [[0 for x in range(m + 1)] for y in range(n + 1)]
    cnt = [[0 for x in range(m + 1)] for y in range(n + 1)]
 
 
    # iterate from i=1 to n and j=1 to j=m
    for i in range(1, n + 1) :
        for j in range(1, m + 1) :
            # stores the maximum of lcs[i-1][j] and lcs[i][j-1]
            lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1])
 
            # when both the characters are equal
            # of s1 and s2
            if (s1[i - 1] == s2[j - 1]):
                cnt[i][j] = cnt[i - 1][j - 1] + 1;
 
            # when length of common segment is
            # more than k, then update lcs answer
            # by adding that segment to the answer
            if (cnt[i][j] >= k) :
                 
                # formulate for all length of segments
                # to get the longest subsequence with
                # consecutive Common Segment of length
                # of min k length
                for a in range(k, cnt[i][j] + 1) :
                     
                    # update lcs value by adding
                    # segment length
                    lcs[i][j] = max(lcs[i][j],lcs[i - a][j - a] + a)
                     
    return lcs[n][m]
 
 
# Driver code 
k = 4
s1 = "aggasdfa"
s2 = "aggajasdfa"
print(longestSubsequenceCommonSegment(k, s1, s2))
 
# This code is contributed by Nikita Tiwari.

C#

// C# program to find the Length of Longest
// subsequence formed by consecutive segments
// of at least length K
using System;
 
class GFG {
 
    // Returns the length of the longest common subsequence
    // with a minimum of length of K consecutive segments
    static int longestSubsequenceCommonSegment(int k, string s1,
                                            string s2)
    {
        // length of strings
        int n = s1.Length;
        int m = s2.Length;
     
        // declare the lcs and cnt array
        int [,]lcs = new int[n + 1,m + 1];
        int [,]cnt = new int[n + 1,m + 1];
     
     
        // iterate from i=1 to n and j=1 to j=m
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
     
                // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
                lcs[i,j] = Math.Max(lcs[i - 1,j], lcs[i,j - 1]);
     
                // when both the characters are equal
                // of s1 and s2
                if (s1[i - 1] == s2[j - 1])
                    cnt[i,j] = cnt[i - 1,j - 1] + 1;
     
                // when length of common segment is
                // more than k, then update lcs answer
                // by adding that segment to the answer
                if (cnt[i,j] >= k)
                {
     
                    // formulate for all length of segments
                    // to get the longest subsequence with
                    // consecutive Common Segment of length
                    // of min k length
                    for (int a = k; a <= cnt[i,j]; a++)
     
                        // update lcs value by adding
                        // segment length
                        lcs[i,j] = Math.Max(lcs[i,j],
                                        lcs[i - a,j - a] + a);
                     
                }
            }
        }
     
        return lcs[n,m];
    }
     
    // driver code to check the above function
    public static void Main()
    {
        int k = 4;
        string s1 = "aggasdfa";
        string s2 = "aggajasdfa";
    Console.WriteLine(longestSubsequenceCommonSegment(k, s1, s2));
    }
}
 
// This code is contributed by vt_m.

Javascript

<script>
 
// JavaScript program to find the Length of Longest
// subsequence formed by consecutive segments
// of at least length K
 
// Returns the length of the longest common subsequence
// with a minimum of length of K consecutive segments
function longestSubsequenceCommonSegment(k, s1, s2)
{
    // length of strings
    var n = s1.length;
    var m = s2.length;
 
    // declare the lcs and cnt array
    var lcs = Array.from(Array(n+1), ()=>Array(m+1).fill(0));
    var cnt = Array.from(Array(n+1), ()=>Array(m+1).fill(0));
 
    // iterate from i=1 to n and j=1 to j=m
    for (var i = 1; i <= n; i++) {
        for (var j = 1; j <= m; j++) {
 
            // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
            lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
 
            // when both the characters are equal
            // of s1 and s2
            if (s1[i - 1] == s2[j - 1])
                cnt[i][j] = cnt[i - 1][j - 1] + 1;
 
            // when length of common segment is
            // more than k, then update lcs answer
            // by adding that segment to the answer
            if (cnt[i][j] >= k) {
 
                // formulate for all length of segments
                // to get the longest subsequence with
                // consecutive Common Segment of length
                // of min k length
                for (var a = k; a <= cnt[i][j]; a++)
 
                    // update lcs value by adding segment length
                    lcs[i][j] = Math.max(lcs[i][j],
                                    lcs[i - a][j - a] + a);
                 
            }
        }
    }
 
    return lcs[n][m];
}
 
// driver code to check the above function
var k = 4;
var s1 = "aggasdfa";
var s2 = "aggajasdfa";
document.write( longestSubsequenceCommonSegment(k, s1, s2));
 
</script>

Producción:  

8

 Complejidad de tiempo : O (N * M), ya que estamos usando bucles anidados para atravesar N * M veces.

Espacio auxiliar : O(N*M), ya que estamos usando espacio adicional para lcs y cnt .

Donde N y M son la longitud de las cuerdas.

Publicación traducida automáticamente

Artículo escrito por Striver y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *