String Loop left Shift

Source: Internet
Author: User

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&AMP;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

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.