Thursday, March 3, 2011

Wap to Find Min. Distance Between Two Character

#include
#include

#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 = '\0',
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="shashank";
char a='s';
char b='k';

int d;

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

Ans. 4

No comments :