🐕实现 strStr() 函数。
给你两个字符串 haystack 和 needle
请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。
如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。
这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = “hello”, needle = “ll”
输出:2
示例 2:
输入:haystack = “aaaaa”, needle = “bba”
输出:-1
示例 3:
输入:haystack = “”, needle = “”
输出:0
提示:
0 <= haystack.length, needle.length <= 5 * 104
haystack 和 needle 仅由小写英文字符组成
🐖思路一:
用双指针 h = 0, n = 0; 两个指针 一开始都在头部
index = 0; index用来记录h的下一个位置
如果 haystack的指针元素 不等于 needle的指针元素
index+1 ,haystack指针等于index指针 needle指针归零
如果 haystack的指针元素 等于 needle的指针元素
haystack和 needle 指针都后移
越界了 判断 n 是否等于 needle的长度 是则返回 index位置 否则返回 -1
上代码
public static int strStr(String haystack, String needle) {
if(needle == "") {
return 0;
}
int h = 0, n = 0;//两个指针 一开始都在头部
int index = 0; //index用来记录h的下一个位置
while(h < haystack.length() && n < needle.length()) {
if(haystack.charAt(h) != needle.charAt(n)) {
index ++;
h = index;
n = 0;
}else {
h++;
n++;
}
}
return n == needle.length() ? index : -1;
}

感觉做的有点差劲啊…
🐒思路二:继续双指针
用双指针 h = 0, n = 0; 两个指针 一开始都在头部
如果 haystack的指针元素 不等于 needle的指针元素
如果 needle指针不为 0
haystack指针 = 自己 - needle指针 + 1 ==> 意思就是让haystack指针 退到 之前第一步走错 的下一步
否则 needle指针为 0
haystack指针 ++
最后无论走哪个分支都要 needle指针归零
如果 haystack的指针元素 等于 needle的指针元素
haystack和 needle 指针都后移
整体越界了
如果 needle指针越界了
返回 haystack指针 - needle 指针的位置
如果haystack指针越界 而 needle没越界
证明找不到字符串 返回-1
上代码
public static int strStr_V2(String haystack, String needle) {
if(needle == "") {
return 0;
}
int h = 0, n = 0;//两个指针 一开始都在头部
while(h < haystack.length() && n < needle.length()) {
if(haystack.charAt(h) != needle.charAt(n)) {
if(n != 0) {
h = (h - n)+1;
}else {
h++;
}
n = 0;
}else {
h++;
n++;
}
}
if(n >= needle.length()) {
return h-n;
}
return -1;
}

思路二 这里也有个小问题 就是如果我再使用else if 进行判断时 程序会超时 虽然结果还是能够正确,但是 超过时间限制…
🐇思路三:截取字符串匹配 (花费空间)
直接 截取字符串进行匹配
依次截取主字符串的 子字符串长度的 字符串 匹配是否 与 子字符串相等 如果不相等 则右移一位继续截取进行匹配 如果最后截取到主字符串长度不够的话 则证明 主字符串中没有匹配子字符串的 字符串 返回 -1
上代码
public static int strStr_V3(String haystack,String needle) {
int len = needle.length();
int total = haystack.length() - len + 1;
for(int start = 0 ; start < total ; start++) {
if(haystack.substring(start, start+len).equals(needle)) {
return start;
}
}
return -1;
}



308

被折叠的 条评论
为什么被折叠?



