Thursday, October 19, 2017

Reverse & Print Common Characters

Two string values S1 and S2 are passed as the input. Reverse string S2 and print the letters which are common in a given index. The letters in S1 and S2 will be in lower case.

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

Output Format:
The first line contains the letters which are common after S2 is reversed.

Boundary Conditions: 2 <= Length of S1 <= 500 2 <= Length of S2 <= 500

Example Input/Output 1:
Input:
energy
genuine
Output:
en
Explanation:
After reversing S2, we get energy, eniuneg
The letters common comparing indices are en (in the first two positions)

Solution:
s,x=input(),input()
i,j=0,len(x)-1
while i<len(s) and j>=0:
    if s[i]==x[j]:
        print(s[i],end='')
    j-=1
    i+=1

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