[字符串轮转(改进)] 对给定的字符串进行轮转,时间复杂度为 O(n) #字符串处理
#include <iostream>
#include <cstring>
using namespace std;
void ReverseString(char* s, int from, int to) {
while(from < to) {
char t = s[from];
s[from++] = s[to];
s[to--] = t;
}
}
void LeftRotateString(char* s, int m) {
int n = strlen(s);
m %= n; //左移 m 位与左移 m%n 等价
ReverseString(s, 0, m - 1); //反转 [0, m-1]
ReverseString(s, m, n - 1); //反转 [m, n-1]
ReverseString(s, 0, n - 1); //整体反转
}
int main() {
char s[] = {"hello"};
cout << s << endl;
LeftRotateString(s, 2);
cout << s << endl;
return 0;
}