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 );}}