leetcode-cn 實現strStr()

題目如圖: java

實現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做者的強大🤣 api

indexOf()
實現strStr()
相關文章
相關標籤/搜索