[Sword Finger Offer] Interview Question 58-II. Left Rotate String

topic

The left rotation operation of the character string is to transfer several characters in front of the character string to the end of the character string. Please define a function to realize the function of the left rotation of the string. For example, if you enter the string "abcdefg" and the number 2, the function will return the result "cdefgab" obtained by rotating two bits to the left.

Example 1:

输入: s = "abcdefg", k = 2
输出: "cdefgab"

Example 2:

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"

限制:1 <= k < s.length <= 10000

Ideas

Code

Time complexity: O (n)
Space complexity: O (1)

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        reverse(s.begin(), s.begin() + n);
        reverse(s.begin() + n, s.end());
        reverse(s.begin(), s.end());
        return s;
    }
};

Guess you like

Origin www.cnblogs.com/galaxy-hao/p/12682420.html