【题目】
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
【解析】
返回在子字符串needle在字符串haystack中第一次出现的位置,如果没有找到则返回-1;
这个题目时间复杂度应该都是O(m*n)。
【代码】
public int strStr(String haystack, String needle) {
int n=haystack.length(),m=needle.length();
if(m==0) return 0;
for(int i=0;i<n;i++)
{
if(i+m>n) break;
for(int j=0;j<m;j++)
{
if(needle.charAt(j)!=haystack.charAt(i+j))
break;
else
if(j==m-1&&needle.charAt(j)==haystack.charAt(i+j))
return i;
}
}
return -1;
}