[Sword refers to offer] Rotate the string to the left, C+ implementation

Original blog post, please indicate the source for reprinting!

This topic Niuke network address

The github address of the code of this question

Index address of this series of articles

# topic

image

# ideas

      Flip the part first, then the whole. Example: abcdefg is partially flipped to bagfedc, and then flipped to cdefgab as a whole.

# code

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string LeftRotateString(string &str, int n)
    {
        int len = str.size();
        // 特殊输入
        if(!str.empty() && n <= len && n >= 0)
        {

            int pFirstStart = 0;
            int pFirstEnd = n - 1;
            int pSecondStart = n;
            int pSecondEnd = len - 1;

            // flip the first n characters of the string
            reverse(str, pFirstStart, pFirstEnd);
            // Flip the back part of the string
            reverse(str, pSecondStart, pSecondEnd);
            // flip the entire string
            reverse(str, pFirstStart, pSecondEnd);

        }
        return str;
    }

    // flip function
    void reverse(string &str, int begin, int end)
    {
        while(begin < end)
        {
            char tmp = str[begin];
            str[begin] = str[end];
            str[end] = tmp;
            begin++;
            end--;
        }
    }
};

intmain()
{
    // test case
    string str = "abcdefg";
    int n = 2;

    // function call
    Solution solution;
    solution.LeftRotateString(str,n);
    cout<<str<<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325297798&siteId=291194637