题目描述:http://blog.youkuaiyun.com/v_july_v/article/details/6322882
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部,如把字符串abcdef左旋转2位得到字符串cdefab。
请实现字符串左旋转的函数,要求对长度为n的字符串操作的时间复杂度为O(n),空间复杂度为O(1)。
1.思路一、暴力移位法
//第一章。左旋转字符串 #include <iostream> #include <string> using namespace std; string str="lisongfeng"; int n=10; void Leftshift_one(string &b,int n) { int i; char ch=b[0]; for (i=1;i<n;i++) b[i-1]=b[i]; b[n-1]=ch; } int main() { Leftshift_one(str,n); cout<<str<<endl; }
思路二、指针翻转法
//第一章。左旋转字符串 #include <iostream> #include <string> #include <algorithm> using namespace std; string str="lisongfeng"; int n=10; int Left_Rotate(string &b,int m) { int len=b.length(); if (m>=len||len==0) return 0; int r1=(n - m) - n % m;; int i; int p=0,q=m; for (i=0;i<r1;i++) { swap(b[p],b[q]); p++; q++; } int r2 = n-q; for (i=0;i<r2;i++) { swap(b[p],b[q]); p++; q++; } return 0; } int main() { int m=2; Left_Rotate(str,m); cout<<str<<endl; }
思路三、递归转换法
。。。。。