左旋转字符串

来源:互联网 发布:办公软件基础知识 编辑:程序博客网 时间:2024/04/30 05:48

问题描述:

定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。

如把字符串abcdef左旋转2位得到字符串cdefab。

请实现字符串左旋转的函数,要求对长度为n的字符串操作的时间复杂度为O(n),空间复杂度为O(1) 


代码:

#include <iostream>#include <string>using namespace std;void Reverse(string::iterator begin,string::iterator end){char tmp;end--;while(begin < end){tmp = *begin;*begin = *end;*end = tmp;begin++;end--;}}void LeftRotateString(string* s,int len){string::iterator begin=(*s).begin();string::iterator end=(*s).end();Reverse(begin,begin+len);Reverse(begin+len,end);Reverse(begin,end);//return s;}int main(int argc, char **argv){string str;string s = "abcdef";int k = 4;if(k < s.length()){//str=LeftRotateString(s,k);LeftRotateString(&s,k);}else{cout<<"the value of k must less than "<<s.length()<<endl;}cout<<s<<endl;return 0;}

原创粉丝点击