Left rotation string

Source: Internet
Author: User

In assembly language, there is a shift instruction called the cyclic left shift (ROL), now there is a simple task, is to use a string to simulate the operation of the command results. For a given character sequence s, you turn the output of the sequence to the left of the K-bit after it is moved. For example, the character sequence s= "Abcxyzdef", which requires the output loop to move left 3 bits after the result, i.e. "XYZDEFABC". Isn't it simple? OK, Fix it!

Idea: Three flips: Assuming that the original array sequence is abcd1234, the sequence of the array required to be transformed is 1234ABCD, that is, the loop shifts 4 bits to the right. After comparison, it is not difficult to see that there are two paragraphs of the order is unchanged: 1234 and ABCD, can be regarded as two of the two paragraphs. The process of moving the K-bit right is to swap the two parts of the array.
The transformation process is accomplished by the following steps:
reverse order abcd:abcd1234→dcba1234;
reverse order 1234:dcba1234→dcba4321;
All reverse: DCBA4321→1234ABCD.

1 classSolution {2  Public:3     stringLeftrotatestring (stringStrintN) {4         intL=str.size ();5         if(l<n)returnstr;6Reverse (str,0, N-1);7Reverse (str,n,l-1);8Reverse (str,0, L-1);9         returnstr;Ten     } One Private: A     voidReversestring&AMP;STR,intLeftintRight ) { -          while(left<Right ) { -             CharC=Str[left]; thestr[left]=Str[right]; -str[right]=C; -left++; -right--; +         } -     } +};

First section, left rotation string
Title Description:

Defines the left rotation of a string: moves several characters in front of the string to the end of the string.
If the string abcdef left rotation 2 bit to get the string cdefab.
A function that implements the left rotation of the string requires that the time complexity of the string operation of length n is o (n) and that the spatial complexity is O (1).  

There is a similar problem with the beauty of programming, let's take a look at it first:

An algorithm is designed to move an array of N elements right through the K-bit, requiring a time complexity of O (N),
And only two additional variables are allowed.

Analysis:

Let's experiment with the simple method of moving the elements in the array to the right one bit at a time, looping k times.
Abcd1234→4abcd123→34abcd12→234abcd1→1234abcd.
RightShift (int* arr, int N, int K)
{
while (k--)
{
int t = arr[n-1];
for (int i = N-1; i > 0; i--)
Arr[i] = arr[i-1];
Arr[0] = t;
}
}

Although this algorithm can realize the loop right shift of the array, but the algorithm complexity is O (K * N), do not meet the requirements of the topic, to continue to explore.

If the array is abcd1234 and the loop is shifted to the right 4 bits, we want to reach the state of 1234ABCD.
It is advisable to set K as a non-negative integer, and when K is a negative integer, move the K-bit to the right, equivalent to the left shift (-K).
The left and right shifts are essentially the same.

Solution One:
There may be a potential hypothesis, k<n. In fact, many times it is true. But strictly speaking, we can not use such "inertia thinking" to think about the problem.
Especially when programming, it is important to consider the problem comprehensively, K may be an integer greater than N, at this time, the above solution needs to be improved.
It is easy to observe the characteristics of the loop right shift, and it is not difficult to find out that each element will return to its own position after the N-bit is shifted right. So, if K > N, the array sequence after the right shift k-n is the same as the result of the right shift K-bit.

In turn, a general rule can be drawn:
The situation after the right shift to K-bit follows the same situation as the right-shift k ' = k-n-bit, as shown in Listing 2-34.
Code Listing 2-34
RightShift (int* arr, int N, int K)
{
K%= N;
while (k--)
{
int t = arr[n-1];
for (int i = N-1; i > 0; i--)
Arr[i] = arr[i-1];
Arr[0] = t;
}
}
It can be seen that the complexity of the algorithm is reduced to O (n^2) After considering the characteristics of cyclic right shift, which is not related to K, and the requirement of the topic is close to one step. But the complexity of the time is not low enough, so let's continue digging around the link between the loop right shift and the array.


Solution Two:
Assuming that the original array sequence is abcd1234, the sequence of the array required to be transformed is 1234ABCD, that is, the loop shifts 4 bits to the right. After comparison, it is not difficult to see that there are two paragraphs of the order is unchanged: 1234 and ABCD, can be regarded as two of the two paragraphs. The process of moving the K-bit right is to swap the two parts of the array.
The transformation process is accomplished by the following steps:
reverse order abcd:abcd1234→dcba1234;
reverse order 1234:dcba1234→dcba4321;
All reverse: DCBA4321→1234ABCD.
Pseudo-code can refer to listing 2-35.
Code Listing 2-35
Reverse (int* arr, int b, int e)
{
for (; b < e; b++, e--)
{
int temp = Arr[e];
Arr[e] = arr[b];
ARR[B] = temp;
}
}

RightShift (int* arr, int N, int k)
{
K%= N;
Reverse (arr, 0, n–k-1);
Reverse (arr, n-k, N-1);
Reverse (arr, 0, N-1);
}

In this way, we can implement the right shift within linear time.

Slightly summed up below:
In the beauty of programming,
(The underlying reason for limiting the idea is that the topic requires: "Only two additional variables are allowed", removing this restriction, and thinking can be like a spring gushing)
1, the first idea, is a character to the right shift, so, the complexity of O (n*k)
2, later, it improved, through this rule: right shift K-bit after the situation, with the right shift k ' = k% n bit after the same situation
Complexity of O (n^2)
3, until the end, it proposed three times the algorithm of flipping, get linear complexity.

Below, you will see that in this chapter we are doing:
1, three flips, direct linear
2, two hands gradually flipped, linear
3. STL's rotate algorithm, linear

OK, now, back to the question of our left spin string, for the question of this left-rotating string, we can consider this as follows:
1.1. Idea One:

For this question, let's take a different perspective and We can do this:
Divide a string into two parts, X and y two parts, define the inverse operation x^t on the string, i.e. invert all the characters of x (for example, x= "abc", then x^t= "CBA"), then we can get the following conclusion: (X^ty^t) ^t=yx. Obviously we can turn this into a string reversal problem.

Is that right? OK, take abcdef This example (very short three sentences, please look closely, understand):
1, first divided into two parts, x:abc,y:def;
2. X->X^T,ABC->CBA, y->y^t,def->fed.
3. (x^ty^t) ^t=yx,cbafed->defabc, which is the entire flip.

I think you should be clear about that.
The code can then write this (it has been tested correctly):

    1. [Email protected] Small Bridge water && July
    2. C code implementation, has been tested correctly.
    3. Http://www.smallbridge.co.cc/2011/03/13/100%E9%A2%98
    4. _21-%e5%b7%a6%e6%97%8b%e8%bd%ac%e5%ad%97%e7%ac%a6%e4%b8%b2.html
    5. July, updated,2011.04.17.
    6. #include <stdio.h>
    7. #include <string.h>
    8. char * INVERT (char *start, char *end)
    9. {
    10. char tmp, *ptmp = start;
    11. while (start! = NULL && end! = NULL && start < end)
    12. {
    13. TMP = *start;
    14. *start = *end;
    15. *end = tmp;
    16. Start + +;
    17. End--;
    18. }
    19. return ptmp;
    20. }
    21. Char *left (char *s, int pos) //pos is the number of characters to be rotated, or the length, under which the main function is tested, pos=3.
    22. {
    23. int len = strlen (s);
    24. Invert (s, S + (pos-1)); //As above, x->x^t, i.e. ABC->CBA
    25. Invert (s + POS, S + (len-1)); //As above, y->y^t, i.e. def->fed
    26. Invert (s, S + (len-1));  //As above, entire flip, (x^ty^t) ^t=yx, i.e. CBAFED->DEFABC.
    27. return s;
    28. }
    29. int main ()
    30. {
    31. Char s[] = "Abcdefghij";
    32. Puts (left (s, 3));
    33. return 0;
    34. }

Transferred from: http://blog.csdn.net/zhoushuai520/article/details/7703368

Left rotation string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.