欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 代码随想录-04-字符串-06.实现strStr()

代码随想录-04-字符串-06.实现strStr()

2025/12/18 9:19:27 来源:https://blog.csdn.net/qq_55675237/article/details/146317862  浏览:    关键词:代码随想录-04-字符串-06.实现strStr()

实现strStr()

实现KMP算法,进行模式串匹配

思路

  • 明确:前缀、后缀、最长公共前后缀的概念
  • 建立next数组,以便在每次匹配不成功时,尽可能将模式串向右滑动
  • 将模式串和文本串进行匹配,文本串是一直向后匹配的,这也就是为什么KMP算法的效率很高的原因

实现难点

  1. 建立next数组
  2. 在模式串和文本串进行匹配的过程中,面对每一轮的处理。1和2的处理方式都是一样的。
    1. 如果不同,根据next数组查找下一个待匹配的位置j = next[j - 1];
    2. 如果相同,就直接j++;

代码

class Solution {
public:int strStr(string haystack, string needle) {if (haystack.size() < needle.size())return -1;vector<int> next(needle.size(), 0);getNext(next, needle);int j = 0;for (int i = 0; i < haystack.size(); i++) {while (j > 0 && haystack[i] != needle[j]) {j = next[j - 1];}if (haystack[i] == needle[j]) {j++;}if (j == needle.size()) {return i - needle.size() + 1;}}return -1;}void getNext(vector<int>& next, string needle) {int j = 0;for (int i = 1; i < needle.size(); i++) {while (j > 0 && needle[i] != needle[j]) {j = next[j - 1];}if (needle[i] == needle[j]) {j++;}next[i] = j;}}
};

Java

class Solution {public int strStr(String haystack, String needle) {if (haystack.length() < needle.length()) {return -1;}int[] next = initNext(needle);int cur = 0;for (int i = 0; i < haystack.length(); i++) {while (cur > 0 && haystack.charAt(i) != needle.charAt(cur)) { // 修正条件cur = next[cur - 1];}if (haystack.charAt(i) == needle.charAt(cur)) { // 修正条件cur++;}if (cur == needle.length()) { // 修正条件return i - needle.length() + 1; // 修正返回值}}return -1;}public int[] initNext(String needle) {int[] res = new int[needle.length()];res[0] = 0;int fast = 0;for (int i = 1; i < needle.length(); i++) {while (fast > 0 && needle.charAt(fast) != needle.charAt(i)) {fast = res[fast - 1];}if (needle.charAt(fast) == needle.charAt(i)) {fast++;}res[i] = fast;}return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词