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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。