如abc,左旋1得到bca,左旋2得到cab
O(n*k)的算法:
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cmath>
int main(){
char s[1005];
int k,len;
while(scanf("%s%d",s,&k) != EOF){
len = strlen(s);
if(k > len){
k = k % len;
}
for(int i = 1;i <= k;i++){
for(int j = 1;j <= len-1;j++){
swap(s[j],s[j-1]);
}
}
printf("%s\n",s);
}
system("pause");
}
O(n)的算法,注意reverse函数,思路:先翻转【0,k-1】区间的字符串,再翻转【k,len-1】的字符串,最后整体翻转【0,len-1】的字符串,调用三次reverse() 函数
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cmath>
void reverse(char s[],int beg,int end){
while(beg < end){
swap(s[beg],s[end]);
beg ++;
end --;
}
}
int main(){
char st[1005];
int k,len;
while(scanf("%s",st) != EOF){
scanf("%d",&k);
len = strlen(st);
if(k > len){
k = k % len;
}
len = strlen(st);
reverse(st,0,k-1);
reverse(st,k,len-1);
reverse(st,0,len-1);
printf("%s\n",st);
}
system("pause");
}