实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,
在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
解析:
方法一:子串逐一比较
最直接的方法 - 沿着字符换逐步移动滑动窗口,将窗口内的子串与 needle 字符串比较
public class leetcode28 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String haystack = "hello";
String needle = "ll";
System.out.println(strStr(haystack,needle));
}
public static int strStr(String haystack,String needle){
int n = haystack.length();
int l = needle.length();
for(int i=0;i<n-l+1;i++){
if(haystack.substring(i,i+l).equals(needle)){
return i;
}
}
return -1;
}
}
方法二:双指针
上一个方法的缺陷是会将haystack所有长度L的子串都与needle比较,实际上不需要。
首先,只有子串的第一个字符跟needle字符串第一个字符相同的时候才比较。
其次,可以一个字符一个字符的比较,一旦不匹配了就立刻终止。
如下图,比较到最后一位发现不匹配,然后开始回溯。
需要注意,pn指针是移动到pn = pn - curr_len + 1的位置,而不是pn = pn - curr_len的位置。
即移动到下一个开始的位置,再依次对比。
算法
移动 pn 指针,直到 pn 所指向位置的字符与 needle 字符串第一个字符相等。
通过 pn,pL,curr_len 计算匹配长度。
如果完全匹配(即 curr_len == L),返回匹配子串的起始坐标(即 pn - L)。
如果不完全匹配,回溯。使 pn = pn - curr_len + 1, pL = 0, curr_len = 0。
class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();
if (L == 0) return 0;
int pn = 0;
while (pn < n - L + 1) {
// find the position of the first needle character
// in the haystack string
while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) ++pn;
// compute the max match string
int currLen = 0, pL = 0;
while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
++pn;
++pL;
++currLen;
}
// if the whole needle string is found,
// return its start position
if (currLen == L) return pn - L;
// otherwise, backtrack
pn = pn - currLen + 1;
}
return -1;
}
}