Title Description: Given a string s[0...n-1], required to move the first k characters of s to the tail of s, such as the string "ABCdef" before the 2 characters ' a ', ' B ' moved to the end of the string, get the new string "Cdefab": That is, the string loop left K.
The algorithm requires: The time complexity is O (n), the space complexity is O (1).
Problem Analysis:
1. The Act of Violent displacement
Each loop moves left 1 bits, calls K times, Time complexity O (kn), Space complexity O (1)
2. Open an array of k+1 lengths and make three copies
S[0...K]→T[0...K]
S[K+1...N-1]→S[0...N-K-1]
T[0...k]→s[n-k ... N-1]
Time complexity O (n), spatial complexity O (k)
None of the two are compliant with algorithmic requirements.
In fact, there is a kind of algorithm that satisfies the condition:
(X ' Y ') ' =yx
such as: abcdef
X=ab X ' =ba
Y=cdef Y ' =fedc
(X ' Y ') ' = (BAFEDC) ' =cdefab
Time complexity O (N), Spatial complexity O (1)
Code implementation:
1#include <iostream>2#include <string>3 using namespacestd; 4 5 voidReverseString (string&STR,intMintN)6 { 7 for(inti = m; I < n; ++i)8 { 9 Chartemp =Str[i];TenStr[i] =Str[n]; OneStr[n] =temp; A--N; - } - } the - intMainintargcConst Char*argv[]) - { - stringstr ="abcdef"; + intLen =str.size (); - intK =2;//Loop left shift 2 bit +K%= Len;//prevent cross-border AReverseString (str,0K1); atReverseString (str, k, Len-1); -ReverseString (str,0, Len-1); -cout << str <<Endl; - return 0; -}
Results:
PS:STL provides a reverse flip string function
String loop shift left