题目:给定两个字符串s1和s2,要求判定s2是否能够被s1做循环移位得到的字符串包含。例如,给定s1=AABCD和s2=CDAA,返回true;给定s1=ABCD和s2=ACBD,返回false。
答:
#include "stdafx.h" #include <iostream>using namespace std;//获取next数组的值 void GetNext(const char* pattern, int length, int *next) {int i = 0;next[i] = -1;int j = -1;while (i < length - 1){if (-1 == j || pattern[i] == pattern[j]){i++;j++;if (pattern[i] != pattern[j]){next[i] = j;}else{next[i] = next[j];}}else{j = next[j];}} }//KMP算法 bool KMP(const char *src, int slength, const char * pattern, int plength, int *next) {int i = 0;int j = 0;while (i < slength && j < plength){if (-1 == j || src[i] == pattern[j]){i++;j++;}else{j = next[j];}}if (j >= plength){return true;}return false; }int _tmain(int argc, _TCHAR* argv[]) {char src[] = "AABCD";char pattern[] = "CDAA";int slength =strlen(src);int plength = strlen(pattern);char *psrc = new char[slength * 2 + 1];strcpy(psrc, src);strcat(psrc, src);*(psrc + slength * 2) = '\0';int *next = new int[plength];GetNext(pattern, plength, next);if (KMP(psrc, slength * 2, pattern, plength, next)){cout<<"字符串"<<src<<"循环移位可以得到"<<pattern<<endl;}else{cout<<"字符串"<<src<<"循环移位得不到"<<pattern<<endl;}delete [] psrc;cout<<endl;return 0; }
运行界面如下: