欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > 【leetcode 26】28.找出字符串中第一个匹配项的下标 | 实现 strStr()==❗不会❗==

【leetcode 26】28.找出字符串中第一个匹配项的下标 | 实现 strStr()==❗不会❗==

2025/2/21 3:23:27 来源:https://blog.csdn.net/weixin_45780075/article/details/145283653  浏览:    关键词:【leetcode 26】28.找出字符串中第一个匹配项的下标 | 实现 strStr()==❗不会❗==

在这里插入图片描述

在一个串中查找是否出现过另一个串,这是KMP的看家本领。

// 方法一
class Solution {public void getNext(int[] next, String s){int j = -1;next[0] = j;for (int i = 1; i < s.length(); i++){while(j >= 0 && s.charAt(i) != s.charAt(j+1)){j=next[j];}if(s.charAt(i) == s.charAt(j+1)){j++;}next[i] = j;}}public int strStr(String haystack, String needle) {if(needle.length()==0){return 0;}int[] next = new int[needle.length()];getNext(next, needle);int j = -1;for(int i = 0; i < haystack.length(); i++){while(j>=0 && haystack.charAt(i) != needle.charAt(j+1)){j = next[j];}if(haystack.charAt(i) == needle.charAt(j+1)){j++;}if(j == needle.length()-1){return (i-needle.length()+1);}}return -1;}
}

版权声明:

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

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

热搜词