22. Microsoft interview questions: Left-hand string

Source: Internet
Author: User

Question:

Define the left rotation operation of the string: Move several characters before the string to the end of the string.

For example, the string "abcdef" is left-byte 2 to get the string "cdefab ". Please implement the left rotation function of the string.

Requires O (n) for the complexity of string operations with a length of n, and the auxiliary memory is O (1 ).


Analysis:

The difficulty of this question is that the secondary memory can only use O (1), which is equivalent to only replacing the characters in the string. To move the string, m * n replacement operations are required, this complexity also comes up, O (n * n ).

You can only think about skills.


The implementation is as follows:

#include
  
   #include
   
    using namespace std;void reverse(char* str, int i, int j){        while( i < j)        {                char chr = str[i];                str[i] = str[j];                str[j] = chr;                i ++;                j --;        }}void leftRotate(char* srcstr, int k){        int len = strlen(srcstr);         if(len <= 1)                return;        k = k%len;        reverse(srcstr, 0, k - 1);        reverse(srcstr, k, len -1);        reverse(srcstr, 0, len -1);}int main(){        char str[] = "abcdef";        cout << "string: " << str << endl;        leftRotate(str, 2);        cout << "rotate string, 2: " << str << endl;        return 0;}
   
  

The output result is as follows:

String: abcdef
Rotate string, 2: cdefab


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.