思路:
1.两个字符串分别定义一个从头开始的指针,并且同时从左向右遍历字符串。
2.如果发现两个指针指向的字符是相同,则
f
l
a
g
flag
flag记录当前的left值,继续同时向右遍历,如果直到
n
e
e
d
l
e
needle
needle遍历结束,都相同,则说明存在
h
a
y
s
t
a
c
k
haystack
haystack存在
n
e
e
d
l
e
needle
needle,则
f
l
a
g
flag
flag值就是首先出现的索引位置。如果在
n
e
e
d
l
e
needle
needle遍历结束前发现存在不同的字符,则left指针重新指向
f
l
a
g
+
1
flag+1
flag+1出,
r
i
g
h
t
right
right重新指向第二个字符串的开始,并且将
f
l
a
g
flag
flag置为-1,再次遍历,。
class Solution {
public int strStr(String haystack, String needle) {
int left = 0;
int right = 0;
int flag = -1;
while((right <= needle.length() - 1 && left <= haystack.length() - 1)||(right==0 && left <= haystack.length() - needle.length()) ){
if(haystack.charAt(left) == needle.charAt(right)){
if(flag == -1)
flag = left;
left++;
right++;
}
else {
if(flag != -1){
left = flag + 1;
right = 0;
flag = -1;
}
else
left++;
}
}
if(right == needle.length())
return flag;
return -1;
}
}
KMP算法,时间复杂度会更低。
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(),m = needle.length();
if(m == 0)
return 0;
int next[] = new int[m];
next[0] = 0;
int i = 0;
for (int j = 1; j < m; j++) {
while (i > 0 && needle.charAt(j) != needle.charAt(i))
i = next[i - 1];
if(needle.charAt(j) == needle.charAt(i))
i++;
next[j] = i;
}
int j = 0;
for (i = 0; i < n; i++) {
while(j > 0 && needle.charAt(j) != haystack.charAt(i))
j = next[j - 1];
if(needle.charAt(j) == haystack.charAt(i))
j++;
if(j == m)
return i - m +1;
}
return -1;
}
}