题目来自编程之美
题目
注意:对字符串S1左旋转和右旋转得到的字符串集合是一样的。因此可以只对S1左旋转或者右旋转,判断其是否包含S2即可。
思路(1)不进行实质的循环移位,当需要对循环移位后的字符串进行比较时,可以让S1的指针从头开始匹配,继而模拟循环移位。
匹配时可以分两类:
(1)字符串S1不进行旋转,而和S2直接匹配。这属于正常的字符串匹配。如果匹配成功,则直接返回true。如果匹配失败,则执行(2)。
(2)字符串S1旋转后的字符串和S2匹配。如S1字符串AABCD和S2字符串CDAA匹配结束时,不能直接返回匹配失败,而是让S1的游标指向字符串S1的的头而重新开始匹配。
代码:
#include <iostream>
#include <assert.h>
using namespace std;
bool IsInclude(char strA[],char strB[])
{
assert(strA && strB);
if (strA == strB && strA == "")
{
return true;
}
int nLenStrA = strlen(strA);
int nLenStrB = strlen(strB);
if (strA < strB)
{
return false;
}
//字符串匹配
int nCurA = 0;
int nCurB = 0;
while(nCurA < nLenStrA && nCurB < nLenStrB)
{
if (strA[nCurA] == strB[nCurB])
{
nCurB++;
nCurA++;
}
else
{
nCurA = nCurA - nCurB + 1;
nCurB = 0;
}
}
if (nCurB == nLenStrB)//不用旋转就直接包含
{
return true;
}
//需要旋转的情况
if (strA[nCurA - 1] == strB[nCurB - 1])
{
nCurA = 0;
while(nCurA < nLenStrA && nCurB < nLenStrB)
{
if (strA[nCurA] == strB[nCurB])
{
nCurB++;
nCurA = (nCurA + 1) % nLenStrA; //指针往前走时,越界时需要回到头继续匹配
}
else
{
//若匹配失败,则需要返回到串A的末端
nCurA = nCurA + nLenStrA - nCurB + 1;
nCurB = 0;
}
}
if (nCurB == nLenStrB)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
int main()
{
// char strA[10] = "AABCD";
// char strB[10] = "CDAA";
// char strA[10] = "ABCD";
// char strB[10] = "ACBD";
// char strA[10] = "A";
// char strB[10] = "A";
// char strA[10] = "CDDBCC";
// char strB[10] = "CCD";
char strA[10] = "DDBCC";
char strB[10] = "CCD";
if (IsInclude(strA,strB))
{
cout<<strA<<" Include "<<strB<<endl;
}
else
{
cout<<strA<<" Not Include "<<strB<<endl;
}
system("pause");
return 1;
}
思路(2):对字符串S1进行拼接,检查拼接后的字符串是否包含S2。如果包含,则肯定能通过移位包含S1.如果不包含,移位后也不能包含S1。
代码:
#include <iostream>
#include <assert.h>
using namespace std;
bool IsInclude(char strA[],char strB[])
{
assert(strA && strB);
if (strA == strB && strA == "")
{
return true;
}
int nLenStrA = strlen(strA);
int nLenStrB = strlen(strB);
int nLenNewStr = nLenStrA * 2;
if (strA < strB)
{
return false;
}
char* pNewStr = new char[nLenNewStr + 1];
strcpy(pNewStr,strA);
strcpy(pNewStr + nLenStrA,strA);
pNewStr[nLenStrA * 2] = 0;
//字符串匹配
int nCurNewStr = 0;
int nCurB = 0;
while(nCurNewStr < nLenNewStr && nCurB < nLenStrB)
{
if (pNewStr[nCurNewStr] == strB[nCurB])
{
nCurB++;
nCurNewStr++;
}
else
{
nCurNewStr = nCurNewStr - nCurB + 1;
nCurB = 0;
}
}
if (nCurB == nLenStrB)
{
return true;
}
else
{
return false;
}
}
int main()
{
// char strA[10] = "AABCD";
// char strB[10] = "CDAA";
char strA[10] = "ABCD";
char strB[10] = "ACBD";
if (IsInclude(strA,strB))
{
cout<<strA<<" Include "<<strB<<endl;
}
else
{
cout<<strA<<" Not Include "<<strB<<endl;
}
system("pause");
return 1;
}