to find minimum distance between two chars in a string

#include <stdio.h> 
#include <limits.h>

#define min(a,b) (a) < (b) ? (a) : (b)


int mindist(const char *s, const char a, const char b)
{
if(!s || !*s)
return INT_MAX;


char lastchar = '',
c;

int lastpos,
i = 0,
m = INT_MAX;

while((c = s[i]))
{
if((c == a) || (c == b))
{

if((c == a && lastchar == b) || (c == b && lastchar == a))
{
m = min(m, i - lastpos);
}
lastchar = c;
lastpos = i;
}
i++;
}
return m;
}

int main()
{
char s[256];

scanf("%s\n", s);

char a, b;

scanf("%c %c", &a, &b);

int d;

if((d = mindist(s, a, b)) != INT_MAX)
{
printf("%d\n", d);
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s