Algorithm interview-learning notes-rotating strings on the left

Source: Internet
Author: User

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

For example, if abcdefg rotates 3 to the right to change to efgabcdAlgorithmYou can achieve this by moving right one by one. The time complexity is K * n, n is the string length, and K is the number of moves.

Our goal is to find an algorithm with a time complexity of N and a space complexity of 1.

(Why does he say that complexity is n ^ 2 after K = K % N? How do I think it should be K % N * n?) haha

Thinking about abcdefg moving three places right, then the final structure is that EFG must have taken the lead and cut the abcd efg. The final result is efg abcd, if the flip result string is dcba gfe, it is the result of both abcd efg's flip. Therefore, the algorithm is summarized as follows:

If K is rotated on the right

1. A0, A1. .. an-k-1 flip

2. An-K,... an-1 flip

3. A0.... an-1 flip

He has a better explanation.

For this question, let's change the angle.,You can do this:
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.

Self-writtenProgramAs follows:

 
# Include <stdio. h> # include <string. h> void swap (char * pA, char * pb) {char TMP = * pA; * pA = * pb; * pb = TMP;} void reverse (char * parray, int F, int t) {While (F <t) {swap (parray + F ++, parray + T --) ;}} int main () {char STR [100]; int nshift, nlen; while (scanf ("% S % d", STR, & nshift )! = EOF) {nlen = strlen (STR); nshift = nshift % nlen; reverse (STR, 0, nLen-nShift-1); reverse (STR, nlen-nshift, nlen-1 ); reverse (STR, 0, nLen-1); printf ("% s \ n", STR );}}

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.