Common Child


Problem Statement :


A string is said to be a child of a another string if it can be formed by deleting 0 or more characters from the other string. Given two strings of equal length, what's the longest string that can be constructed such that it is a child of both?

For example, ABCD and ABDC have two children with maximum length 3, ABC and ABD. They can be formed by eliminating either the D or C from both strings. Note that we will not consider ABCD as a common child because we can't rearrange characters and ABCD  ABDC.

Function Description

Complete the commonChild function in the editor below. It should return the longest string which is a common child of the input strings.

commonChild has the following parameter(s):

s1, s2: two equal length strings
Input Format

There is one line with two space-separated strings, s1 and s2.

Constraints

1  <=   | s1 | , | s2 |  <=  5000
All characters are upper case in the range ascii[A-Z].
Output Format

Print the length of the longest string s, such that  is a child of both s1 and s2.



Solution :



title-img


                            Solution in C :

In  C :




#include<stdio.h>
#include<string.h>
char str1[5005],str2[5005];
int c[5005][5005];
int main()
{
  int i,j,m,n;
  scanf("%s %s",str1+1,str2+1);
  m=strlen(str1+1);
  n=strlen(str2+1);
  for(i=1;i<=m;i++)c[i][0]=0;
  for(j=0;j<=n;j++)c[0][j]=0;
  for(i=1;i<=m;i++)
    for(j=1;j<=n;j++)
      {
	if(str1[i]==str2[j])
	  c[i][j]=c[i-1][j-1]+1;
	else if(c[i-1][j]>=c[i][j-1])
	  c[i][j]=c[i-1][j];
	else
	  c[i][j]=c[i][j-1];
      }
  printf("%d\n",c[m][n]);
  return 0;
}
                        


                        Solution in C++ :

In  C++ :





#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int dp[5005][5005];

int main() {
    string a, b;
    cin >> a >> b;
    
    for(int i = 0; i < a.size(); ++i)
        for(int j = 0; j < b.size(); ++j)
            if(a[i] == b[j])
                dp[i + 1][j + 1] = dp[i][j] + 1;
            else
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
    
    cout << dp[a.size()][b.size()];
    return 0;
}
                    


                        Solution in Java :

In   Java ;





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
		String s1 = s.nextLine();
		String s2 = s.nextLine();
		int[][] lengths = new int[s1.length()+1][s2.length()+1];
		
		for (int i = 1; i < lengths.length; i++) {
			for (int j = 1; j < lengths.length; j++) {
				if (s1.charAt(i-1) == s2.charAt(j-1)) {
					lengths[i][j] = lengths[i-1][j-1] + 1;
				}
				else if (lengths[i][j-1] > lengths[i-1][j]) {
					lengths[i][j] = lengths[i][j-1];
				}
				else {
					lengths[i][j] = lengths[i-1][j];
				}
			}
		}
		System.out.println(lengths[lengths.length-1][lengths.length-1]);
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :






def llis(a, b):
    m = len(a)
    n = len(b)
    prev = [0 for x in range(n + 1)]
    for i in range(1, m + 1):
        curr = [0 for x in range(n + 1)]
        for j in range(1, n + 1):
            curr[j] = max(prev[j], curr[j - 1])
            if a[i - 1] == b[j - 1]:
                curr[j] = max(curr[j], prev[j - 1] + 1)
        prev = curr
    return curr[n]
    
if __name__ == '__main__':
    a = input().strip()
    b = input().strip()
    c = set(a) & set(b)
    a = "".join([x for x in a if x in c])
    b = "".join([x for x in b if x in c])
    print(llis(a, b))
                    


View More Similar Problems

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →