Algorithm


Problem link- https://www.spoj.com/problems/CPRMT/

CPRMT - Common Permutation

no tags 

 

Given two strings of lowercase letters, a and b, print the longest string x of lowercase letters such that there is a permutation of x that is a subsequence of a and there is a permutation of x that is a subsequence of b.

Input

Input file contains several lines of input. Consecutive two lines make a set of input. That means in the input file line 1 and 2 is a set of input, line 3 and 4 is a set of input and so on. The first line of a pair contains a and the second contains b. Each string is on a separate line and consists of at most 1000 lowercase letters.

Output

For each set of input, output a line containing x. If several x satisfy the criteria above, choose the first one in alphabetical order.

Example

Sample input:
pretty
women
walking
down
the
street
 
Sample output:
e
nw
et 

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include<bits/stdc++.h>
using namespace std;

#define LL long long int
#define LD long long double


int main(){
    
    while(!cin.eof()){
        string A,B;
        getline(cin,A);
        getline(cin,B);
        sort(A.begin(),A.end());
        sort(B.begin(),B.end());
        int l1=A.length();int l2 =B.length();
        if(l1>l2){
            string temp = A;
            A=B;B=temp ;
            int temp1 =l1;
            l1= l2;
            l2= temp1;
            //swaping integers
        }
        
        if(A[0]>B[l2-1]){
            cout<<"\n";
            continue;
        }
        string result;
        int i = 0,m = 0 ;
        while(i<l1 && m<l2){
            int flg=0;
            int j = m;
            while(j<l2){
                if(A[i]==B[j]){
                    result+=A[i];
                    flg=1;
                    m=j;
                    break;
                }
                j++;
            }
            if(flg==1){m++;}
            i++;
        }
        result+="\n";
        cout<<result;

    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
pretty
women
walking
down
the
street

Output

x
+
cmd
e
nw
et
Advertisements

Demonstration


SPOJ Solution-Common Permutation-Solution in C, C++, Java, Python

Previous
SPOJ Solution - Test Life, the Universe, and Everything - Solution in C, C++, Java, Python