【题目】
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;
}
本文介绍了一个简单的strStr()函数实现方法,该函数用于查找一个字符串(haystack)中首次出现另一个字符串(needle)的位置。如果找到,则返回该位置的索引;否则返回-1。文章提供了详细的代码实现及解析。
520

被折叠的 条评论
为什么被折叠?



