Rotate string to determine whether the string is from rotation

Keywords: github

subject

1. To implement a function, k characters in a left-handed string can be used.
BCDA is obtained by turning one character left of ABCD
ABCD left two characters to get CDAB
2. . determine whether a string is a string after rotation of another string.
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

thinking

1. All left-handed and right-handed can be regarded as left-handed, and right-handed k is equivalent to left-handed size - k (size is string length). Store the second half of the non rotating part to an empty array, and then the rotating part of the first half

2,. Look at the picture

Code

You can go My github Download this code

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

char * RotateString(char *arr, int num, int size);
int CheckString(char *arr1, char *arr2, int size1, int size2);
int CheckCycle(char *p, char *q);

int main()
{
    char arr1[] = "ABCDEFG";
    char arr2[] = "CDEFGAB";
    int num = 5;
    int size1 = sizeof(arr1);
    int size2 = sizeof(arr1);
    printf("%s\n", RotateString(arr1, num, size1));
    //Output string after rotation
    printf("%d\n", CheckString(arr1, arr2, size1, size2));
    //Returns whether it is a rotated string. It is 1, not 0
    system("pause");
    return 0;
}

char * RotateString(char *arr, int num, int size)
{
    char * p = (char*)malloc(sizeof(char)*size);//Allocate n spaces for array storage after rotation
    char * head = p;//Head pointer, save head
    int i = 0;
    for (i = num; i < size-1; i++)
    {
        *p++ = *(arr + i);//CD without rotating part is stored in p first
    }
    for (i = 0; i < num; i++)
    {
        *p++ = *(arr + i);//Rotate part AB into array p
    }
    *p = '\0';//Last given \ 0 end array
    return head;
}

int CheckString(char *arr1, char *arr2, int size1, int size2)
{
    char *p = arr1;//p points to arr1, q points to arr2
    char *q = arr2;
    while (*q != '\0')
    {
        if (*p == *q)
        {
            if (CheckCycle(p, q))//Determine whether to rotate. If the rotation returns to 1
            {
                return 1;
            }
        }
        q++;
    }
    return 0;//If it runs here, the string does not match the rotation, and 0 is returned
}

int CheckCycle(char *p, char *q)
{
    while (*q != '\0')
    {
        if (*p != *q)//Unequal returns 0 directly, equal continues to judge until q points to the last character
        {
            return 0;
        }
        p++;
        q++;
    }
    return 1;
}

Posted by jrbilodeau on Sat, 02 May 2020 09:18:01 -0700