给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
思路一:这道题让我们在一个字符串中找另一个字符串第一次出现的位置,那我们首先要做一些判断,如果子字符串为空,则返回0,如果子字符串长度大于母字符串长度,则返回-1。然后我们开始遍历母字符串,我们并不需要遍历整个母字符串,而是遍历到剩下的长度和子字符串相等的位置即可,这样可以提高运算效率。然后对于每一个字符,我们都遍历一遍子字符串,一个一个字符的对应比较,如果对应位置有不等的,则跳出循环,如果一直都没有跳出循环,则说明子字符串出现了,则返回起始位置即可,
public int strStr_2(String haystack, String needle) {
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int h = haystack.length(),n = needle.length();
for(int i = 0; i <= h-n; i++){//不需要遍历完,因为到后面长度就不符合了
int j = 0;
for(j = 0; j < n; j++){
if(haystack.charAt(i+j) != needle.charAt(j))
break;
}
System.out.println(j);
if(j == n)
return i;
}
return -1;
}
思路二:substring .....
public int strStr_3(String haystack, String needle) {
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int h = haystack.length(),n = needle.length();
for(int i = 0; i <= h-n; i++){
if(haystack.substring(i, i+n).equals(needle)){
return i;
}
}
return -1;
}
思路二:https://www.cnblogs.com/zhangtianq/p/5839909.html
private void GetNext(String needle,int next[])
{
int pLen = needle.length();
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1)
{
//p[k]表示前缀,p[j]表示后缀
if (k == -1 || needle.charAt(j) == needle.charAt(k))
{
++k;
++j;
next[j] = k;
}
else
{
k = next[k];
}
}
}
public int KmpSearch(String haystack, String needle) //kmp
{
if(haystack.length() < needle.length())
return -1;
if(needle.length() == 0)
return 0;
int i = 0;
int j = 0;
int[] next = new int[needle.length()];
GetNext(needle, next);
int sLen = haystack.length();
int pLen = needle.length();
while (i < sLen && j < pLen)
{
//①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++
if (j == -1 || haystack.charAt(i) == needle.charAt(j))
{
i++;
j++;
}
else
{
//②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]
//next[j]即为j所对应的next值
j = next[j];
}
}
if (j == pLen)
return i - j;
else
return -1;
}