字符串移位包含
題目:給定兩個(gè)字符串s1和s2,要求判定s2是否能夠被s1做循環(huán)移位得到的字符串包含。例如,給定s1=AABCD和s2=CDAA,返回true;給定s1=ABCD和s2=ACBD,返回false。
答:
#include "stdafx.h" #include <iostream>using namespace std;//獲取next數(shù)組的值 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<<"循環(huán)移位可以得到"<<pattern<<endl;}else{cout<<"字符串"<<src<<"循環(huán)移位得不到"<<pattern<<endl;}delete [] psrc;cout<<endl;return 0; }運(yùn)行界面如下:
轉(zhuǎn)載于:https://www.cnblogs.com/venow/archive/2012/09/03/2668295.html
總結(jié)
- 上一篇: C#编程语言(六):枚举类型与结构类型
- 下一篇: ZendStudio8的注册码