leetcode-cn 实现strStr()

题目如图:

其实这道题相当于让我们自己手写indexOf(),平时用惯了api,手写起来不是很容易,我自己就换了好几种写法,代码如下:

private static int strStr(String haystack, String needle) {
	if (haystack == null || needle == null) {
		return -1;
	}
	int needleLength = needle.length();
	if (needleLength == 0) {
		return 0;
	}
	int stackLength = haystack.length();
	if (needleLength > stackLength) {
		return -1;
	}
	int i = 0, j = 0, count = 0;
	// i < stackLength - (needleLength - j - 1) 目的是为了减少查找次数
	// 例如 A = "aabbccdef" B = "def" 当 j = 0 的时候最多只能到A串的'd',后面的“ef”没必要查找
	// 当 j = 1 的时候 最多只能到 A 中的 'e' 相当于动态限制
	for (; j < needleLength && i < stackLength - (needleLength - j - 1); i++, j++) {
		while (haystack.charAt(i) != needle.charAt(j) && i < stackLength - (needleLength - j - 1)) {
			// 全部遍历了还没找到 只针对于 needleLength = 1 或者两个字符串长度相等
			if (i == stackLength - 1 || needleLength == stackLength) {
				return -1;
			}
			if (count == 0) {
				// 没有找到过,就一直找下去
				++i;
			} else {
				// 找到过,但是中间某个不匹配了,要重新找 即 j 指针指向 0
				// 例如 abccbcdd 和 bcd 之前匹配到 bc count = 2 
				// 然后 c 和 d 不匹配,所以需要重新匹配,i 从之前的 index 即 (i - count) 再加 1 位出发就好
				j = 0;
				i = (i - count) + 1;
				count = 0;
			}
		}
		if (++count == needleLength && i < stackLength - (needleLength - j - 1)) {
			return i - count + 1;
		}
	}

	return -1;
}
复制代码

看了第一名的代码,愈发觉得jdk作者的强大?

转载于:https://juejin.im/post/5cfdfd6fe51d4510aa0114d7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值