Programmer's Programming technology learning notes--rotate left string

Source: Internet
Author: User

Programmer's Programming technology learning notes--rotate left string 1. Title Description

Given a string, it is required to move several characters in front of the string to the end of the string, such as the string "ABCdef" before the 2 characters ' a ' and ' B ' moved to the end of the string, so that the original string into the string "Cdefab". Write a function that requires an O (n) time complexity for a string operation of length n and an O (1)space complexity .

2. Solution 1: Violent left shift

This solution is simple, rough and easy to think! You are not to think of K characters, I first move a bit, and then move a function to run K-Times is good ~ ~ wherein the shift 1-bit of the program to write, take the first character, dump, the back of the n-1 shift, dump the word descriptors Finally, can.

We use the following illustration to help illustrate:


The algorithm thought and process steps of this solution we all agreed. Let's analyze its complexity: time complexity O (kn), space complexity O (1). Gee, it's been a long time! Does not meet the requirements of the topic, no wonder called violence left shift ... Anyway, we're going to give the implementation code for this solution.

#include <iostream>using namespace std;string leftShift1 (string str, int n, int k) {    char temp;    int i;    while (k--)  //Shift K-times    {        temp=str[0];        for (I=1; i<n; i++)        {            str[i-1]=str[i];        }        str[n-1]=temp;    }    return str;} int main () {    string str= "abcdef";    int n=str.length ();  String length    int k=2;  The number of digits that need to be left shifted    if (k>=n) k%=n;  Consider the robustness of    str=leftshift1 (str, n, k);    cout<<str<<endl;    return 0;}

3. Solution 2: Wasted Space

You'll know by the name of this method that the spatial complexity of this method should be relatively high. The algorithm is also very simple: create a new equal-length character array strarray, first copy the previous K-bit characters to the last K-bit of strarray, similar to the n-k bit after copying, you can.

As shown in the following:


The spatial complexity of this method is O (n), the time complexity is O (n), the time complexity meets the requirement, then the space complexity is not enough. The implementation code is as follows:

String leftShift2 (string str, int n, int k) {    string str2= "";    Str2=str2+str.substr (k, n-k);  Use of String type + connection and substr substring    str2=str2+str.substr (0, k);    return str2;}

4. Solution 3: Hand-Crank Method

This is called the hand-crank method, then what is the hand-crank method? The July blog shows a diagram:

It's Magical ~ ~ Is this process a lot like string flipping?

The above process is mathematically translated into:

Dividing a string into X and y two parts, defining a reversal operation on each part of the string, such as x^t, which reverses all the characters of x (for example, x= "abc", then x^t= "CBA"), then the following conclusion is obtained: (x^ty^t) ^t=yx, obviously solves the problem of string inversion.

For example, String abcdef, to let def flip to the head of ABC, just follow these 3 steps:

First of all, the original string is divided into two parts, namely X:abc,y:def;

The X is reversed, x->x^t,:abc->cba; Y is reversed, y->y^t, that is: def->fed.

Reverse the results of the above steps to get the string x^ty^t, that is, the inverse of the string cbafed two parts (CBA and fed) to give reversal, cbafed get DEFABC, formally expressed as (x^ty^t) ^t=yx, which realizes the entire reversal.

We also use the following illustration:

The process of reversal is also relatively simple, for example, from head to tail is the need to reverse the string, we first give the head to temp, and then tail to Head,head++,temp to tail,tail--, has been running to Head>tail.

Thus, the spatial complexity of the method is O (1) and the time complexity is O (n+n) =o (n). Why is O (n+n)? Because there are 3 reversals, the first two add up to O (n), the third is the full length reversal, and the other O (n), so you can.

Below we give the code:

String reversestring (String str,int head,int tail) {    while (Head < tail)    {        char t = str[head];        str[head++] = Str[tail];        str[tail--] = t;    }    return str;} String leftShift3 (string str, int n, int k) {    k%= n;               To move the left more than n bits, then the%n is equivalent to    str=reversestring (str, 0, k-1);//Invert [0..k-1], apply to the example above, is x->x^t, that    is ABC->CBA Str=reversestring (str, k, n-1); Invert [k.. N-1], such as y->y^t, i.e. def->fed    str=reversestring (str, 0, n-1);//Invert [0..n-1], i.e. the entire reversal, (x^ty^t) ^t=yx, cbafed-> Defabc.    return str;}

5. Extrapolate

1), linked list rollover. Give a list and a number of k, for example, the list is 1→2→3→4→5→6,k=2, then flip after 2→1→6→5→4→3, if k=3, flip 3→2→1→6→5→4, if k=4, flip after 4→3→2→1→6→5, with the program to achieve.

2), write the program, in the original string to move the end of the string m characters to the head of the string, requires: the length of the string of n is the complexity of the operation time O (n), the space Complexity of O (1). For example, the original string is "Ilovebaofeng", m=7, and the output is: "Baofengilove".

3), Word flip. Enter an English sentence, flipping the order of the words in the sentence, but the order of the characters in the word is constant, and the words in the sentence are separated by spaces. For simplicity, punctuation is treated like ordinary letters. For example, enter "I am a student.", then output "student." A am I ".


Programmer's Programming technology learning notes--rotate left string

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.