头图

title: Daily practice (32): Rotate the string left

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/07


Daily practice (32): Rotate a string to the left

The left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to implement the function of left rotation of strings. For example, input the string "abcdefg" and the number 2, the function will return the result "cdefgab" obtained by left-rotating two places.

Example 1:

Input: s = "abcdefg", k = 2

Output: "cdefgab"

Example 2:

Input: s = "lrloseumgh", k = 6

Output: "umghlrlose"

limit:

1 <= k < s.length <= 10000

Source: LeetCode

Link: https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof

Method 1: Divide

Algorithm flow:

A good way to concatenate and rotate strings is to multiply the string into a long string of two identical strings, and then rotate.

//1
string reverseLeftWords(string s, int n) {
    int len = s.size();
    s += s;
    return s.substr(n, len);
}
//2
string reverseLeftWords(string s, int n) {
    s += s;
    return s.substr(n, s.size() / 2);
}
//3
string reverseLeftWords(string s, int n) {
    return (s+s).substr(n, s.size());
}

Method 2: Delete

Algorithm flow:

Insert the first k characters into the string, and then delete the first k characters. Space 0(1)

string reverseLeftWords(string s, int n) {
    for (int i = 0; i < s.size(); i++) {
        s.push_back(s[i]);
    }
    s.erase(0, n);
    return s;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记