题目
你知道的。
分析
分析不来。
代码
void OutputArray(int* pArr, int iLen) { for (int i = 0; i < iLen; i++) { printf("%d ", pArr[i]); } printf(" "); } void GetNextValue(char const* szPattern, int iLen, int* pNextArr) { int i = 0; pNextArr[i] = -1; int j = -1; while (i < iLen - 1) { if (j == -1 || szPattern[i] == szPattern[j]) { ++i; ++j; if (szPattern[i] != szPattern[j]) pNextArr[i] = j; else pNextArr[i] = pNextArr[j]; } else j = pNextArr[j]; } } int KMP(const char * szTarget, const char * szPattern) { int iSrcLen = strlen(szTarget); int iPatternLen = strlen(szPattern); int* pNextArr = new int[iPatternLen]; GetNextValue(szPattern, iPatternLen, pNextArr); OutputArray(pNextArr, iPatternLen); int targetIndex = 0; int patternIndex = 0; while (targetIndex < iSrcLen && patternIndex < iPatternLen) { if (patternIndex == -1 || szTarget[targetIndex] == szPattern[patternIndex]) { ++targetIndex; ++patternIndex; } else { patternIndex = pNextArr[patternIndex]; } } delete[] pNextArr; if (patternIndex >= iPatternLen) return targetIndex - iPatternLen; else return -1; } void GetNextValue2(char const* szPattern, int iLen, int* pNextArr) { int index = 0; pNextArr[0] = -1; for (int i = 1; i < iLen; ++i) { index = pNextArr[i - 1]; while (index >= 0 && szPattern[index + 1] != szPattern[i]) { index = pNextArr[index]; } if (szPattern[index + 1] == szPattern[i]) { pNextArr[i] = index + 1; } else { pNextArr[i] = -1; } } } int KMP2(const char* szTarget, const char* szPattern) { const int iSrcLen = strlen(szTarget); const int iPatternLen = strlen(szPattern); int* pNextArr = new int[iPatternLen]; GetNextValue2(szPattern, iPatternLen, pNextArr); OutputArray(pNextArr, iPatternLen); int patternIndex = 0; int targetIndex = 0; while (patternIndex < iPatternLen && targetIndex < iSrcLen) { if (szTarget[targetIndex] == szPattern[patternIndex]) { ++targetIndex; ++patternIndex; } else if (patternIndex == 0) { ++targetIndex; } else { patternIndex = pNextArr[patternIndex - 1] + 1; } } delete[] pNextArr; if (patternIndex == iPatternLen) return targetIndex - patternIndex; else return -1; }