题目描述
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:“sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:“leeto” 没有在 “leetcode” 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string
self-题解
package middium;
import java.util.Scanner;
public class Solution28 {
public static int strStr(String haystack,String needle){
int index=0;
if(haystack==null||needle==null||haystack.length()<needle.length()){
return -1;
}
int len_n=needle.length();
int len_h=haystack.length();
for(int i=0;i<haystack.length();i++){
if(haystack.charAt(i)==needle.charAt(0)){
index=i;//第一个相匹配的字符的下标
break;//注意这个break不能漏
}
}
int temp=index;
boolean flag=true;
for(int j=1;j<len_n;j++){
if(haystack.charAt(++temp)!=needle.charAt(j)){//无法ton过所有的测试用例,对于测试用例:"mississippi" "issip" 无法通过
flag=false;//字符匹配不上
return -1;
}else{
flag=true;
}
if(flag==true&&j==len_n-1){
return index;
}
}
return index;
}
public static void main(String [] args){
String haystack="";
String needle="";
Scanner in=new Scanner(System.in);
haystack=in.nextLine();
needle=in.nextLine();
int ans=strStr(haystack,needle);
System.out.println(ans);
}
}
题解1
class Solution {
public int strStr(String haystack, String needle) {
int n=haystack.length();
int m=needle.length();
for(int i=0;i+m<=n;i++){//注意这里的等号
boolean flag=true;
for(int j=0;j<m;j++){
if(haystack.charAt(i+j)!=needle.charAt(j)){
flag=false;
break;
}
}
if(flag){
return i;
}
}
return -1;
}
}
KMP算法
class Solution {
// KMP 算法
// ss: 原串(string) pp: 匹配串(pattern)
public int strStr(String ss, String pp) {
if (pp.isEmpty()) return 0;
// 分别读取原串和匹配串的长度
int n = ss.length(), m = pp.length();
// 原串和匹配串前面都加空格,使其下标从 1 开始
ss = " " + ss;
pp = " " + pp;
char[] s = ss.toCharArray();
char[] p = pp.toCharArray();
// 构建 next 数组,数组长度为匹配串的长度(next 数组是和匹配串相关的)
int[] next = new int[m + 1];
// 构造过程 i = 2,j = 0 开始,i 小于等于匹配串长度 【构造 i 从 2 开始】
for (int i = 2, j = 0; i <= m; i++) {
// 匹配不成功的话,j = next(j)
while (j > 0 && p[i] != p[j + 1]) j = next[j];
// 匹配成功的话,先让 j++
if (p[i] == p[j + 1]) j++;
// 更新 next[i],结束本次循环,i++
next[i] = j;
}
// 匹配过程,i = 1,j = 0 开始,i 小于等于原串长度 【匹配 i 从 1 开始】
for (int i = 1, j = 0; i <= n; i++) {
// 匹配不成功 j = next(j)
while (j > 0 && s[i] != p[j + 1]) j = next[j];
// 匹配成功的话,先让 j++,结束本次循环后 i++
if (s[i] == p[j + 1]) j++;
// 整一段匹配成功,直接返回下标
if (j == m) return i - m;
}
return -1;
}
}
> 作者:AC_OIer
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solution/shua-chuan-lc-