Point to Offer 58-II. Rotate string left

Topic describes

Left-rotation of a string moves several characters from the beginning to the end of the string. Define a function to rotate the string left. For example, if you enter the string “abcdefg” and the number 2, the function will return “cdefgab” as a result of the left rotation.

Example 1:

Input: s = "abcdefg", k = 2 Output: "cdefgab"Copy the code

Example 2:

Input: s = "lrloseumgh", k = 6 Output: "umghlrlose"Copy the code

Train of thought

  • The first n characters are reversed
  • Then invert the remaining characters
  • Invert all characters

code


class Solution
{
public:
    string reverseLeftWords(string s, int n)
    {

        int size = s.size(a);// Call the system function reverse
        // reverse the first n characters
        // reverse the rest of the characters
        // reverse all characters
        
        // reverse(s.begin(), s.begin() + n);
        // reverse(s.begin() + n, s.end());
        // reverse(s.begin(), s.end());
        
        reverseStr(s, 0, n - 1);
        reverseStr(s, n, s.size() - 1);
        reverseStr(s, 0, s.size() - 1);
        return s;
    }

    // Custom functions
    void reverseStr(string &s, int start, int end)
    {
        while (start < end)
        {
            chartmp = s[start]; s[start] = s[end]; s[end] = tmp; start++; end--; }}};Copy the code