0

I wrote this code to find if string s2 is a substring of string s1. However I'm getting time limit exceeded. How can I make my algorithm better?

#include<stdio.h>

 int main()
{
char s1[20], s2[20];

scanf("%s %s", s1,s2);


char *p, *q, *count;
p=s1;
q=s2;
int i=21;

do{

   if(*p==*q)                 /* the strings are compared */
   {
   count=p;
    while(*p==*q)
        {(*p)++; (*q)++;}

    if(*q=='\0')
   {
    i=0;
      while(&s1[i]!= count)         /* count =p to get the index where the substring match starts */
      i++;
      printf("%d",i);
      break;
    }
    else
    { q=s2; (*p)--;}
  }     
 }
while((++(*p))!='\0');

if(i==21)                    /* if s2 is not a substring print -1 */
printf("-1");

 return 0;  
}
2
Contributors
2
Replies
16
Views
3 Years
Discussion Span
Last Post by neha_8
0

At lines 21 and 35 you have used this construct (*a)++ where a is a char*. Think about what this does ...

Because of the * in (*a)++ you do not increament the pointer a but rather what it points to, a char. You almost certain meant to increment the pointer like this a++. Because of this as soon as the condition at line 20 is true, lines 20-21 form an infinite loop because if x == y then (x+1) == (y+1).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.