5.6 实现strStr() (串)——【LeetCode】

在这里插入图片描述

package com.string.java;

public class six {

	//方法一:
	//基于滑动窗口的算法
	public int strStr(String haystack, String needle) {
		int m = needle.length();
		// 当 needle 是空字符串时我们应当返回 0
		if(m == 0) {
			return 0;
		}
		int n = haystack.length();
		if(n < m) {
			return -1;
		}
		int i = 0;
		int j = 0;
		while(i < n - m + 1) {
			//找到首字母相等
			while(i < n && haystack.charAt(i) != needle.charAt(j)) {
				i++;
			}
			if(i == n) {//没有找到
				return -1;
			}
			//执行到此处,说明存在相等字符,继续遍历后续字符,判断是否相等
			i++;
			j++;
			while(i < n && j < m && haystack.charAt(i) == needle.charAt(j)) {
				i++;
				j++;
			}
			if(j == m) {//说明找到
				return i - j;//即i-m
			}else {//未找到 此处看到匹配不成功的话这里只是将needle向右移动了一下 重新匹配
				i -= j-1;
				j = 0;
			}
		}
		return -1;
	}

	//方法二:KMP
	public int strStr1(String haystack, String needle) {
		if(needle.length() == 0) {
			return 0;
		}
		int[] next = new int[needle.length()];
		getNext(next, needle);//获取needle的部分匹配值表
		
		for (int i = 0, j = 0; i < haystack.length(); i++) {
            while (j > 0 && needle.charAt(j) != haystack.charAt(i)) {
            	j = next[j - 1];//更新j值
            }
            if (needle.charAt(j) == haystack.charAt(i)) {
            	j++;
            }
            if (j == needle.length()) {
            	return i - needle.length() + 1;
            }
        }
		return -1;
	}
	
	//获取到一个字符串(子串) 的部分匹配值表
	private void getNext(int[] next, String dest) {

		next[0] = 0; //如果字符串是长度为1 部分匹配值就是0
		for(int i = 1,j = 0; i < dest.length();i++) {
			//当dest.charAt(i) != dest.charAt(j) ,我们需要从next[j-1]获取新的j
			//直到我们发现 有  dest.charAt(i) == dest.charAt(j)成立才退出
			//这是kmp算法的核心点
			while(j > 0 && dest.charAt(i) != dest.charAt(j)) {
				j = next[j-1];
			}
			//当dest.charAt(i) == dest.charAt(j) 满足时,部分匹配值就是+1
			if(dest.charAt(i) == dest.charAt(j)) {
				j++;
			}
			next[i] = j;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DZSpace

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值