LeetCode Question 28 Implementing StrStr()
Implement the strStr() function.
Given a haystack string and a needle string, find
the first position (0-based) in the haystack string where the needle string occurs. Returns -1 if not present.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
This topic needs to pay attention to some edge data, which needs special attention!
Java
public int strStr(String haystack, String needle) {
if (needle.isEmpty())
return 0;
int i = 0, j = 0;
for (i = 0; i <= haystack.length() - needle.length(); i++) {
for (j = 0; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j))
break;
}
if (j == needle.length())
return i;
}
return -1;
}
C++
class Solution
{
public:
int strStr(string haystack, string needle)
{
if(needle.length()==0)return 0;
int i,j;
int len_1 = haystack.length();
int len_2 = needle.length();
for(i=0; i<=(len_1-len_2); i++)
{
for(j=0; j<needle.length(); j++)
{
if(haystack[i+j]!=needle[j])
break;
}
if(j==needle.length())
return i;
}
return -1;
}
};
I encountered a bug here, and it took a long time to find it, which is very strange:
int main()
{
Solution s;
string a="";
string b = "a";
cout<<a.length()<<endl;
cout<<b.length()<<endl;
cout<<a.length()-b.length()<<endl;
return 0;
}
The output is:
0
1
4294967295
Shouldn't the third output be: -1? So I tried to use the a.size() function again, and the result was the same. In fact, the size() function in string is the same as the length() function.