实现strStr()函数。
返回字符串needle在字符串haystack中第一次出现的下标,如果找不到,返回-1
1. 借助于java中内置的相关函数
public int strStr(String haystack, String needle)
{
return haystack.indexOf(needle);
}
2. 常规思路
遍历串haystack中的每一个字符,如果与串needle中的第一个字符相同,就记录下当前haystack串的下标k,
并同时更新haystack串和needle串的下标,如果成功遍历到串needle的尾部,则k即为子串needle的起始
下标,否则,让串haystack从下标k+1开始,继续寻找子串needle,直到到达串haystack的结尾,如果,
找不到就返回-1。
public int strStr(String haystack, String needle)
{
int pos = -1;
int len1 = haystack.length();
int len2 = needle.length();
int i = 0;
int j = 0;
int k = 0;
// 如果needle串比haystack串要长
if (len2 > len1)
{
return pos;
}
// 串needle为空时,返回0
if (len2 == 0)
{
return 0;
}
for (i=0; i<len1; i++)
{
k = i;
for (j=0; j<len2 && i<len1; j++)
{
if (haystack.charAt(i) == needle.charAt(j))
{
i++;
}
else
{
break;
}
}
// 说明在haystack串中,找到了needle串,返回起始位置即可
if (j == len2)
{
return k;
}
i = k;
}
return pos;
}
3.
// 该代码根据java中indexOf源码改编而成
public int strStr03(String source, String target)
{
int sourceCount = source.length();
int targetCount = target.length();
// 如果target字符串长度为0,则返回搜索的起始下标
if (targetCount == 0)
{
return 0;
}
char first = target.charAt(0);
int max = sourceCount - targetCount; // 两个字符串相差的长度
for (int i=0; i<=max; i++)
{
/*Look for first character.*/
if (source.charAt(i) != first)
{
while (++i <= max && source.charAt(i) != first);
}
/*Found first character, now look at the rest of v2*/
if (i <= max)
{
int j=i+1;
int end = j + targetCount - 1; // 继续在source中查找的最大长度
for (int k=1; j<end && source.charAt(j) == target.charAt(k); j++, k++);
if (j == end)
{
/*Found whole string.*/
return i;
}
}
}
return -1;
}