2023-11-13
28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)
思路2:kmp算法-》求字符串的最大前后缀长度问题
class Solution { public int strStr(String haystack, String needle) { //暴力法 //双指针 //kmp算法 //kmp int n = haystack.length(), m = needle.length(); if (m == 0) { return 0; } int[] pi = new int[m]; for (int i = 1, j = 0; i < m; i++) { while (j > 0 && needle.charAt(i) != needle.charAt(j)) { j = pi[j - 1]; } if (needle.charAt(i) == needle.charAt(j)) { j++; } pi[i] = j; } for (int i = 0, j = 0; i < n; i++) { while (j > 0 && haystack.charAt(i) != needle.charAt(j)) { j = pi[j - 1]; } if (haystack.charAt(i) == needle.charAt(j)) { j++; } if (j == m) { return i - m + 1; } } return -1; } }
标签:下标,charAt,int,needle,28,++,字符串,haystack,pi From: https://www.cnblogs.com/youye9527/p/17830420.html