Amazon Interview Question
Software Engineer / DevelopersAny comments on improving my implementation are welcome!
char* my_strstr(const char* s1, const char* s2)
{
char* p1 = const_cast<char*>(s1);
char* p2 = const_cast<char*>(s2);
int len = 0;
while(*p1)
{
if(*p1 == *p2)
{
p2++;
len++;
}
else
{
if(*p2 == '\0')
{
return p1-len;
}
}
p1++;
}
if(*p1==*p2)
return p1-len;
return NULL;
}
int main ()
{
char * str1 = "mmmmmmmmmgood" ;
char * str2 = "mmmgood" ;
char * p = str1 ;
char * p2 = str2 ;
char * start = NULL ;
while ( *p != '\0' && *p2 != '\0')
{
if( *p == *p2){
p2++ ;
if( start == NULL) start = p ;
p++ ;
}
else if ( start != NULL){
//reset
p2 = str2 ;
start = NULL ;
}
else
p++ ;
}
printf ("%s = " , start) ;
}
General comment regarding some of these code snippets -- what's with the casting of const char * to a char *?? You'll need to understand the difference between char * const (or const char * const) and const char * to pass any interview I give. In none of these cases the input string is, or should be, modified. Leave the const be!
Here is the java brute force solution
// Return: Starting position of n within h or -1 if n don't occur within h
// h = main String eg: needle
// n = search string eg: eed
int strstr(String h, String n)
{
if (n.length > h.length)
{
return -1;
}
// O(n^2) soln
// Lets save some time instead of iterating through the whole h.
// If h is 8 chars, and n is 5 characters, don't need to check 4th character.
for (int i = 0; i <= (h.length - n.length) ; i++)
{
int j = 0;
for (j < n.length; j++)
{
if (h.charAt(i + j) != n.charAt(j))
{
break;
}
}
if (j == n.length)
{
return i;
}
}
}
int strstr(String h, String n)
{
if (n.length > h.length)
{
return -1;
}
// O(n^2) soln
// Lets save some time instead of iterating through the whole h.
// If h is 8 chars, and n is 5 characters, don't need to check 4th character.
for (int i = 0; i <= (h.length - n.length) ; i++)
{
int j = 0;
for (j < n.length; j++)
{
if (h.charAt(i + j) != n.charAt(j))
{
break;
}
}
if (j == n.length)
{
return i;
}
}
}
#include <iostream>
- Jobseeker March 21, 2010using namespace std;
int main()
{
char *t = "This is lib";
char *p = "HSC";
char *s, *soln;
soln = NULL;
s = p;
int count = strlen(p);
cout<< " the strlen is " << count;
while(*t != '\0')
{
if(*t == *p)
{
t++;
p++;
if(*p == '\0')
{
soln = t - count;
}
}
else
{
p = s;
t++;
}
}
if(soln == NULL)
{
cout << "pattern not present";
}
else
cout<<"pattern found at " << soln;
return 0;
}
Please comment on my logic n implementation