实现 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() 定义相符。
我写出来的笨比解法的思路就是逐个比较,当第一个相同的时候就接着和剩下的进行比较,如果全都一样就返回当前角标。
class Solution {
public int strStr(String haystack, String needle) {
char[] nee = needle.toCharArray();
char[] hay = haystack.toCharArray();
int neelength = nee.length;
int haylength = hay.length;
if(neelength==0)return 0;
for(int i = 0 ;i<=haylength-neelength;i++){
if(hay[i] == nee[0]){
boolean flag = true;
int neei = 1;
for(int j = i+1;j<i+neelength;j++){
if(hay[j]!=nee[neei]){
flag = false;break;}
if(neei<neelength-1) neei++;
}
if(flag==true)return i;
}
}
return -1;
}
}
题解中的双指针法
首先,只有子串的第一个字符跟 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。
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。