Programmer programming art (algorithm volume): Chapter 1, left rotating string

Source: Internet
Author: User

Preface
I have sorted out the 100 questions series for Microsoft and other companies, including the sorting of original questions, resource uploads, post maintenance, answer sorting, errata, correction and optimization work, including 80 newly sorted questions in the future, A total of 180 interview questions have been around for half a year.

For details about all the 180 interview questions, see: yundun was born and swept through Csdn [Evaluation of Microsoft and other data structures + algorithm interview 180 questions].

I have always felt that any of these 180 questions deserves repeated thinking, research, revision, and optimization. Due to the rush of time, the limitations of the initial understanding, and the limited level of the previous answers, the answers to these 180 interview questions are worth further discussion and improvement.

Here, I want to write another series for these 180 interview questions, which is called the crazy series of interview questions for programmers. As you can see, I'm sure I want to write a series of things, which will be written permanently.

"He is like a wind, and many people gradually stop, but he has been flying, always flying ...."

OK. This series starts with 100 questions and left-rotated strings in the Microsoft interview 26th questions I originally prepared. I hope to give a thorough and in-depth explanation of this question. However, all the code below is only correct in all tests, and there is still a lot of optimization work to be done. Anyone is welcome. Thank you.

Section 1: Left-rotated string
Description:

Define the left rotation operation of the string: Move several characters before the string to the end of the string.
For example, the string abcdef is rotated two places to the left to obtain the string cdefab.
Please implement the left rotation function of the string. the time complexity for string operations with the length of n is O (n), and the space complexity is O (1 ).

The beauty of programming has such a similar problem. Let's take a look:

Design an algorithm to shift the right K-Bit of an array containing N elements. The time complexity is O (N ),
Only two additional variables are allowed.

Analysis:

First, let's try a simple method. We can shift the elements in the array one bit right each time and iterate K times.
Abcd1234 → 4abcd123 → 34abcd12 → 234abcd1 → 1234 abcd.
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 right shift of the array loop, the complexity of the algorithm is O (K * N), which does not meet the requirements of the question. We should continue to explore.

If the array is abcd1234 and the loop shifts four places to the right, the expected status is 1234 abcd.
K is a non-negative integer. When K is a negative integer, K is shifted to the right, which is equivalent to the Left shift (-K.
The Left shift and right shift are essentially the same.

Solution 1:
In the beginning, we may have such a potential assumption: K <N. In fact, this is also true in many cases. But strictly speaking, we cannot use this "inertial thinking" to think about problems.
In programming, it is very important to fully consider the problem. K may be an integer greater than N. At this time, the above solution needs to be improved.
After carefully observing the characteristics of the right shift of the loop, it is not difficult to find that each element will return to its position after shifting N places to the right. Therefore, if K> N, the sequence of the array after right shift K-N is the same as the result of right shift K bit.

Then a general rule can be obtained:
The case after shifting K-bit right is the same as that after shifting K' = K % N-bit right, as shown in the code list 2-34.
// Code List 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 the feature of moving the right of the loop is added. This is irrelevant to K and is a step closer to the requirement of the question. However, the time complexity is not low enough. Let's continue to explore the associations between arrays before and after the right shift of the loop.


Solution 2:
Assume that the original array sequence is abcd1234 and the transformed array sequence is 1234 abcd, that is, four digits are shifted to the right of the loop. After comparison, it is not difficult to see that there are two segments in the same order: 1234 and abcd. we can regard these two segments as two parts. The K-bit shifting process is to swap the two parts of the array.
Perform the following steps to complete the transformation:
Sort abcd in reverse order: abcd1234 → dcba1234;
1234 in reverse order: dcba1234 → dcba4321;
All in reverse order: dcba4321 → 1234 abcd.
For pseudocode, see List 2-35.
// Code List 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 operation in linear time.

Summary:
The beauty of programming,
(The root reason for limiting the thinking in the book is that the question requires: "And only two additional variables are allowed". With this restriction removed, the idea can be sprayed like a spring)
1. The first idea is to shift the right of a character. Therefore, the complexity is O (N * K)
2. Later, it improved. Through this rule: the case after the right shift of K bit is the same as the case after the right shift of K' = K % N
Complexity: O (N ^ 2)
3. Until the end, it proposed a three-way flip algorithm to obtain linear complexity.

Next, you will see that our practice in this chapter is:
1. triplicate, direct Linearity
2. The two pointers are gradually flipped and linear.
3. stl rotate algorithm, linear

Okay. Now, let's go back to the left-rotated string problem. For this left-rotated string problem, we can consider it as follows:
1.1. Train of Thought 1:

To solve this problem, we can change the angle:
Divides a string into two parts: X and Y. The inverse operation X ^ T is defined on the string, that is, all characters of X are reversed (for example, X = "abc ", then, we can draw the following conclusion: (X ^ TY ^ T) ^ T = YX. Obviously, this can be converted to the string inversion problem.

No? OK. Take the abcdef example as an example (a very short sentence, please read it carefully and understand it at a Glance ):
1. There are 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, that is, the entire flip.

I think, now you should renew it.
Then, the code can be written as follows (the test is correct ):

View plaincopy to clipboardprint?
// Copyright @ Xiaoqiao journal & July
// C code implementation. The test is correct.
// Http://www.smallbridge.co.cc/2011/03/13/100%E9%A2%98
// Configure
// July, updated, 2011.04.17.
# Include <stdio. h>
# Include <string. h>

Char * invert (char * start, char * end)
{
Char tmp, * ptmp = start;
While (start! = NULL & end! = NULL & start <end)
{
Tmp = * start;
* Start = * end;
* End = tmp;
Start ++;
End --;
}
Return ptmp;
}

Char * left (char * s, int pos) // pos is the number or length of characters to be rotated. In the following main function test, pos = 3.
{
Int len = strlen (s );
Invert (s, s + (pos-1); // As shown above, X-> X ^ T, that is, abc-> CBA
Invert (s + pos, s + (len-1); // As shown above, Y-> Y ^ T, that is, def-> fed
Invert (s, s + (len-1); // as above, the entire flip, (X ^ TY ^ T) ^ T = YX, that is, cbafed-> defabc.
Return s;
}

Int main ()
{
Char s [] = "abcdefghij ";
Puts (left (s, 3 ));
Return 0;
}

1.2 answer: In V0.3, question 26th

Related Article

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.