leetcode-cn 實現strStr()

題目如圖:
實現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作者的強大🤣
indexOf()
實現strStr()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章