Saturday, December 2, 2017

First N Common Characters

Two string values S1, S2 are passed as the input. The program must print first N characters present in S1 which are also present in S2.

Input Format:
The first line contains S1. The second line contains S2. The third line contains N.

Output Format:
The first line contains the N characters present in S1 which are also present in S2.

Boundary Conditions: 2 <= N <= 10 2 <= Length of S1, S2 <= 1000

Example Input/Output 1:
Input:
abcbde
cdefghbb
3
Output:
bcd
Note:
b occurs twice in common but must be printed only once.

Solution:
#include <iostream>
using namespace std;
int main()
{
 string x,y;
 int i,n,c[26]={0};
 cin>>x>>y>>n;
 for(i=0;i<y.length()-1;i++)
   c[y[i]-'a']=1;
 for(i=0;i<x.length();i++)
   if(c[x[i]-'a']==1&&(n--)>0)
    {
        cout<<x[i];
        c[x[i]-'a']++;
    }
}
Share: