1. Implement a function that can rotate k characters in a left-handed string.
BCDA is obtained by turning one character left of ABCD
ABCD left two characters to get CDAB
Train of thought:
We can first turn the k characters that should be rotated, then turn other characters, and finally turn them together to realize the rotation of characters.
Code:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
void Reverse(char *p,char *q)//Flipping strings
{
while(p < q)
{
char a = *p;
*p = *q;
*q = a;
p++;
q--;
}
}
void Leftturn(char *a, int len,int n)//Rotate character function
{
Reverse(&a[0],&a[n-1]);//Flip first k characters
Reverse(&a[n],&a[len-1]);//Flip other characters
Reverse(&a[0],&a[len-1]);//Flip all characters together
}
int main()
{
char arr[] = "ABCDE";
int s = 0;
int sz = strlen(arr);
printf("Please enter the number of characters you want to rotate\n");
scanf("%d",&s);
Leftturn(arr,sz,s);
printf("%s",arr);
return 0;
}
2. Judge whether a string is a string after another string rotation.
For example: given s1 = AABCD and s2 = BCDAA, return 1, given s1=abcd and s2=ACBD, return 0
AABCD left one character to get ABCDA
AABCD left two characters to get BCDAA
AABCD right turns a character to get DAABC
Train of thought:
On the basis of the previous question, we make right-handed, and use strcmp function to verify.
Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Reverse(char *p,char *q)
{
while(p < q)
{
char a = *p;
*p = *q;
*q = a;
p++;
q--;
}
}
int Judgeturn(char a[],char b[], int len)
{
int i = 0;
char *p = malloc(len);//Open up a dynamic space
// Levo
for(i=0; i<len; i++)
{
strcpy(p,a);//Copy a string to dynamic p
Reverse(&p[0],&p[i]);
Reverse(&p[i+1],&p[len-1]);
Reverse(&p[0],&p[len-1]);
if(strcmp(p,b) == 0)//Comparison and verification of rotated string p and string b
{
return 1;
}
}
// Dextral rotation
for(i=0; i<len; i++)
{
strcpy(p,a);
Reverse(&p[len-i],&p[len-1]);
Reverse(&p[0],&p[len-i-1]);
Reverse(&p[0],&p[len-1]);
if(strcmp(p,b) == 0)
{
return 1;
}
}
return 0;
free(p);
}
int main()
{
char arr[] = "ABCDE";
char s[] = "DEABC";
int sz = strlen(arr);
int ret = 0;
ret = Judgeturn(arr,s,sz);
if( ret == 1)
{
printf("It is obtained by rotating the original string\n");
}
else
{
printf("Not derived from the rotation of the original string\n");
}
return 0;
}