Practice of flipping questions


insert image description here

1. Write a function to implement string flipping

Description
Write a function to flip a string
Input description:
Input a string
Output description:
Output the reversed string
insert image description here
Writing method 1:
This method is to define begin and end, exchange the values ​​of begin and end at the same time, and begin++ after the exchange , end–, it ends until begin <= end

void Rote(int*nums,int numsSize )
{
    
    
    int begin = 0;
    int end = numsSize - 1;
    while (begin <= end)
    {
    
    
        int temp = nums[begin];
        nums[begin++] = nums[end];
        nums[end--] = temp;
    }
}

Writing method 2:
The idea of ​​this method is similar to the above, but the writing method is different

void reverse_string(int*nums,int numsSize)
{
    
    
    int len=numsSize;
    for(int i=0;i<len/2;i++)//对称交换
    {
    
    
        char temp=s[len-1-i];
        s[len-1-i]=s[i];
        s[i]=temp;
    }
}

Writing method 3:
The above two methods are in-situ rotation, this method is off-site rotation, that is, to create an array, directly put the data in the array from the back into another array, and then copy it directly, this method is relatively simple , I will not write the code

Second, the rotation array

189. Rotating arrays
insert image description here
In fact, if you understand the above questions thoroughly, you can basically understand this question, but you need to think of a special idea 1.
Reverse the entire string
2. Reverse the interval as the substring of the first k
3 .Reverse the interval from k to the end of the substring
and then you can
use the method of the first question above, this question is easy to do
Here I only write the first method of writing

void fun(int *nums,int begin,int end)
{
    
    
    while(begin<=end)
    {
    
    
        int temp=nums[begin];
        nums[begin++]=nums[end];
        nums[end--]=temp;
    }
}
void rotate(int* nums, int numsSize, int k){
    
    
    k%=numsSize;
    fun(nums,0,numsSize-k-1);
    fun(nums,numsSize-k,numsSize-1);
    fun(nums,0,numsSize-1);
    for(int i=0;i<numsSize-1;i++)
    {
    
    
        printf("%d",nums[i]);
    }
}

Summarize

This article is short in length, but as long as you master the ideas of these two questions, there will be basically no problem with flipping the question

Guess you like

Origin blog.csdn.net/Ruiren_/article/details/129086785