整体思路:根据之前的文章C语言实现字符串左旋,那么这就很简单了,只需要判断s2字符串是不是双倍s1字符串的字串就可以了,在之前的基础上加上一个strstr()函数就可以进行判断了。但前提必须是s2字符串的长度和s1字符串的长度一样,才有比较的必要,因此在之前进行一次字符长度的比较,如果一样长,再进行判断。
- 代码如下 (环境:Visual Studio 2017)
//例如:给定s1 = AABCD和s2 = BCDAA,返回1,给定s1 = abcd和s2 = ACBD,返回0.
//AABCD左旋一个字符得到ABCDA
//AABCD左旋两个字符得到BCDAA
//AABCD右旋一个字符得到DAABC
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <assert.h>
#pragma warning(disable:4996);
int LeftRotate(char str[], char D[], char value[])
{
assert(str);
assert(D);
char *d = D;
char *s = str;
if (strlen(str) != strlen(value))
{
return 0;
}
while (*d)
{
d++;
}
while (*s)
{
*d++ = *s++;
}
return strstr(D, value);
}
int main()
{
char str[] = "abcd123";
char data[64];
char value[] = "123abcd";
strcpy(data,str);
if(LeftRotate(str, data, value))
{
printf("%s 是 %s 旋转之后的字符串!\n",value, str);
}
else
{
printf("%s 不是 %s 旋转之后的字符串!\n", value, str);
}
system("pause");
return 0;
}