JZ43 左旋转字符串

本文最后更新于:2022年4月9日 中午

image-20211010145647113

Solution

  • 拼接再截取
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
string LeftRotateString(string str, int n) {
int len = str.size();
if (len == 0 || n <= 0) return str;
n %= len;
str += str; // !循环问题,拼接
return str.substr(n, len);
}
};
  • 截取再重排
1
2
3
4
5
6
7
8
9
class Solution {
public:
string LeftRotateString(string str, int n) {
int len = str.size();
if (len == 0 || n <= 0) return str;
n %= len;
return str.substr(n, len - n) + str.substr(0, n);
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!