Minimum Distance Between Alphabets

 

              Minimum Distance Between Alphabets  

 

 Minimum Distance Between Alphabets :Given a string S and two alphabets C1 and C2 present in S, find the minimum distance D  between C1 and C2 in S.

Input Format:
The first line will contain S.
The second line will contain C1 and C2 separated by a space.
Output Format:
The first line will contain D.
Boundary Conditions:
2 <= Length of S <= 100
Example Input/Output 1:
Input:
spaceship
c s
Output:
1

Code:

C++:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string s;
cin>>s;
char a,b;
cin>>a;
cin>>b;
int m=s.length(),flag=0,d=0;
for(int i=0;i<s.length();i++)
{
    if(s[i]==a||s[i]==b)
    {
        if(flag==1&&d!=0)
        {
        if(d<m)
        m=d;
        d=0;
        }
        else
        flag=1;
    }
    if(flag==1)
    d++;
}
cout<<m-1;
}


Java:

import java.util.*;
import java.lang.*;
public class Hello {
 
    public static void main(String[] args) {
                   Scanner sc=new Scanner(System.in);
                   String str=sc.next();
                   char a=sc.next().charAt(0);
                   char b=sc.next().charAt(0);
                   int d1=str.indexOf(a);
                   int d2=str.indexOf(b);
                   int ld1=str.lastIndexOf(a);
                   int ld2=str.lastIndexOf(b);
                   int diff=Math.abs(d1-d2);
                   int diff1=Math.abs(ld1-ld2);
    if(diff<diff1)
        System.out.print(diff-1);
    else   
        System.out.print(diff1-1);
          }
}

Small logic change is there!!

Please do comment If u have any Queries!

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *