Breaking

Tuesday 19 September 2017

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:

  1. import java.util.*;
    public class Hello {

    public static void main(String[] args) {
    //Your Code Here
    Scanner scan=new Scanner(System.in);
    String a=scan.next();
    char x=scan.next().charAt(0);
    char y=scan.next().charAt(0);
    int n=0,m=0,o=0,p=0,c=0;
    for(int i=0;i=0;i--)
    {
    if(y==a.charAt(i))
    {
    m=i;
    break;
    }
    }
    if(n>m)
    {
    o=n;
    p=m;
    }
    else{
    o=m;
    p=n;
    }
    for(int i=p+1;i<o;i++)
    {
    c++;
    }
    System.out.print(c);


    }
    }

    ReplyDelete
  2. #include
    #include
    #include
    #include
    #include
    using namespace std;
    int main(int argc, char** argv)
    {
    char s[100];
    cin>>s;
    char a,b;
    cin>>a>>b;
    int i,i1,j=0,k=0,n=strlen(s);
    int ind_a[100],ind_b[100];
    for(i=0;iabs(ind_a[i]-ind_b[i1]-1))
    //min=
    min[x++]=abs(abs(ind_a[i]-ind_b[i1])-1);
    //cout<<min[x-1];
    }
    }
    sort(min,min+x);
    cout<<min[0];
    }



    //2 test cases failed out of 7

    ReplyDelete

Like