9. Longest repeating subsequence(similar to LCS)

9. Longest repeating subsequence(similar to LCS)


Problem link :- click here


package programs;

public class String__9
{

	/*
	 	Longest repeating subsequence
	 		1)   s = "AABEBCDD" 		2)   str = "AXXXY"
	 		output = "ABD"		          output = "XX"
	 		
	 	To understand this problem we need to know Longest common subsequence(LCS)
	 			s1 = "ABCDGH"    and   s2 = "AEDFHB"
	 				     output = "ADH"
	 				     
	 	in this problem we have to find the longest no. of common elements from both the
	 	strings that are in SAME ORDER
	 	
	 	APPROACH ------>   DYNAMIC PROGRAMMING
	 	
	 	we will take a matrix of length      s1.length()+1       &         s2.length()+1
	 	our OUTPUT will be the last element of the matrix      
	 	one row extra because we are initiating the value of a block(i-row j-column)
	 		based on the previous row(i-1) and previous column(j-1)
	 	and yes our first row and first column will be zero
	 	
	 	so our actual count of index will be from 1 in matrix 
	 	but in string it will be as usual  from 0
	 	so if we finding the value of         mat[i][j]
	 	we have to consider the characters at index        i-1        &       j-1
	 	
	 	while iterating
	 	we compare the values of           s1[i-1]       &         s2[j-1]
	 	if  they are same           we will take the diagonal element and add 1 and store
	 			mat[i][j] = mat[i-1][j-1] + 1
	 	if they are not same       we will store maximum of the left cell and top cell
	 			mat[i][j] = Math.max( mat[i][j-1] ,  mat[i-1][j]  )
	 	
	 	
	 	In our main problem we have to use a character only once for a subsequence
	 	so lets add a condition in if statement       i != j
	 */
	
	static int longestRepeatingSubsequence(String s)
	{
		//lets store the string to a character array
		char str[] = s.toCharArray();
		int n= str.length;
		
		int mat[][] = new int[n+1][n+1];
		
		//first row zero
		for(int i=0; i<n+1; i++)
			mat[0][i] = 0;
		
		//first column zero
		for(int i=0; i<n+1; i++)
			mat[i][0] = 0;
		
		for(int i=1; i<n+1; i++)
		{
			for(int j=1; j<n+1; j++)
			{
				if(str[i-1] == str[j-1]     &&     i != j )
					mat[i][j] = mat[i-1][j-1] + 1;
				else
					mat[i][j] = Math.max( mat[i][j-1], mat[i-1][j] );
			}
		}
		
		return mat[n][n];
	}
	
	public static void main(String[] args)
	{
		String s = "AABEBCDD";
		
		int ans = longestRepeatingSubsequence(s);
		System.out.println("longest subsequence : " + ans);
	}

}

Time complexity :- O(n^2)
Space complexity :- O(n^2)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree