# I got a problem but don't know why , can anyone explain?

• I first coded like this:

``````int strStr(string haystack, string needle) {
int i,j;
for(i=0;i<haystack.length()-needle.length()+1;++i)
{
for(j=0;j<needle.length();++j)
{
if(haystack[i+j] != needle[j])
break;
}
if(j == needle.length())
return i;
}
return -1;
}
``````

I summited the code,got runtime error,last executed input is "abb" "abaaa",then I went to custom testcase and input "abb" "abaaa" and got 48...while the expected answer should be -1.

I changed the code a little bit like this:

``````int strStr(string haystack, string needle) {
int i,j;
int m = haystack.length(),n = needle.length();
for(i=0;i<m-n+1;++i)
{
for(j=0;j<n;++j)
{
if(haystack[i+j] != needle[j])
break;
}
if(j == n)
return i;
}
return -1;
}
``````

And I got the right answer.

The only difference is that I defined m,n instead of using x.length() in the loop.
Can anyone explain why this happen?

• ``````size_t string.length();
``````

size_t is defined as unsigned integer, which always is a positive integer.

size_t(1) - size_t(3) = 0xFFFFFFFF - 2;

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.