脚本宝典收集整理的这篇文章主要介绍了28. 实现 strStr(),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-strstr 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private int[] getNext(String needle) {
int[] next = new int[needle.length()];
next[0] = -1;
int i = 0, j = -1;
while (i < needle.length() - 1) {
if (j == -1 || needle.charAt(i) == needle.charAt(j)) {
if (needle.charAt(++i) == needle.charAt(++j)) {
next[i] = next[j];
} else {
next[i] = j;
}
} else {
j = next[j];
}
}
return next;
}
public int strStr(String haystack, String needle) {
if (haystack == null || haystack.length() == 0) {
return needle == null || needle.length() == 0 ? 0 : -1;
}
if (needle == null || needle.length() == 0) {
return 0;
}
int[] next = getNext(needle);
int i = 0, j = 0;
while (i < haystack.length() && j < needle.length()) {
if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
++i;
++j;
} else {
j = next[j];
}
}
return j == needle.length() ? i - j : -1;
}
}
以上是脚本宝典为你收集整理的28. 实现 strStr()全部内容,希望文章能够帮你解决28. 实现 strStr()所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。