实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-strstr
方法一:子串逐一比较
最直接的方法 - 沿着字符换逐步移动滑动窗口,将窗口内的子串与 needle 字符串比较。
public static int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();
for (int start = 0; start < n - L + 1; ++start) {
if (haystack.substring(start, start + L).equals(needle)) {
return start;
}
}
return -1;
}
方法二:双指针
上一个方法的缺陷是会将 haystack 所有长度为 L 的子串都与 needle 字符串比较,实际上是不需要这么做的。
首先,只有子串的第一个字符跟 needle 字符串第一个字符相同的时候才需要比较。
其次,可以一个字符一个字符比较,一旦不匹配了就立刻终止。
如下图所示,比较到最后一位时发现不匹配,这时候开始回溯。需要注意的是,pn 指针是移动到 pn = pn - curr_len + 1 的位置,而 不是 pn = pn - curr_len 的位置。
这时候再比较一次,就找到了完整匹配的子串,直接返回子串的开始位置 pn - L。
算法
- 移动 pn 指针,直到 pn 所指向位置的字符与 needle 字符串第一个字符相等。
- 通过 pn,pL,curr_len 计算匹配长度。
- 如果完全匹配(即 curr_len == L),返回匹配子串的起始坐标(即 pn - L)。
- 如果不完全匹配,回溯。使 pn = pn - curr_len + 1, pL = 0, curr_len = 0。
public static int strStr2(String haystack, String needle) {
//needle和haystack的长度
int L = needle.length(), n = haystack.length();
if (L == 0) return 0;
//haystack当前的指针索引
int pn = 0;
while (pn < n - L + 1) {
//在haystack字符串中找到与needle字符串第一个字符相等的字符的位置
while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) pn++;
//计算最大匹配字符串
int currLen = 0;//匹配的长度
int pL = 0;//needle当前的指针索引
//通过 pn,pL,curr_len 计算匹配长度
while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
pn++;
pL++;
currLen++;
}
//如果needle字符串被找到,返回needle字符串出现的第一个位置
if (currLen == L) return pn - L;
//否则,回滚pn
pn = pn - currLen + 1;
}
return -1;
}