28. 找出字符串中第一个匹配项的下标

题目:

https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

思路:使用KMP算法

Java代码如下:

import java.util.Scanner;

class Solution {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
String t=scanner.next();
System.out.println(strStr(s,t));
}
public static void GetNextval(String t,int nextval[]){
int j=0,k=-1;
nextval[0]=-1;
while (j<t.length()-1){
if(k-1||t.charAt(j)t.charAt(k)){
j++;
k++;
if (t.charAt(j)!=t.charAt(k)){
nextval[j]=k;
}else {
nextval[j]=nextval[k];
}
}else {
k=nextval[k];
}
}
}
//KMP算法
public static int strStr(String haystack, String needle) {
int nextval[]=new int[needle.length()];
int i=0,j=0;
GetNextval(needle,nextval);
while (i<haystack.length()&&j<needle.length()){
if (j-1||haystack.charAt(i)needle.charAt(j)){
i++;
j++;
}else {
j=nextval[j];
}
}
if (j>=needle.length()){
return i-needle.length();
}else {
return -1;
}
}
}

posted @   hhh_666  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示