题目:
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。
如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数。
要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)。
答案:
//20130208
#include <iostream>
#include <string>
using namespace std;
void reverseStr(string &s, int m, int n);
int main()
{
string s="abcdef";
int n = s.size() - 2;
reverseStr(s,0,s.size() - 1);
reverseStr(s,0,n - 1);
reverseStr(s, n, s.size() - 1);
return 0;
}
void reverseStr(string &s,int m, int n)
{
char c;
while (m < n)
{
c = s[m];
s[m] = s[n];
s[n] = c;
++m;
--n;
}
}