题目:
字符串的左旋转操作是把字符串前面的若干字符转移到字符串的后面。请定义一个函数实现字符串左旋转操作的功能,
比如:输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab";
思路:
这道题和翻转单词顺序很相似。思路也是一样的。
第一步:翻转整个字符串"abcdefg",得到"gfedcba"
第二步:翻转字符串“gfedc”,得到"cdefg"
第三步:翻转字符串"ba",得到"ab"
或者:
第一步:翻转字符串“ab”,得到"ba";
第二步:翻转字符串"cdefg",得到"gfedc";
第三步:翻转字符串"bagfedc",得到"cdefgab";
代码:
#include <iostream>
#include <string.h>
using namespace std;
void Reverse(char* pBegin,char* pEnd){
if(pBegin==NULL || pEnd==NULL)
return;
char tmp;
while(pBegin<pEnd){
tmp=*pBegin;
*pBegin=*pEnd;
*pEnd=tmp;
pBegin++;
pEnd--;
}
}
char* LeftRotateString(char* pStr,int n){
int len=strlen(pStr);
if(pStr==NULL || n<=0 || n>=len)
return pStr;
char* pFirstStart=pStr;
char* pFirstEnd=pStr+n-1;
char* pSecondStart=pStr+n;
char* pSecondEnd=pStr+len-1;
Reverse(pFirstStart,pFirstEnd);
Reverse(pSecondStart,pSecondEnd);
Reverse(pFirstStart,pSecondEnd);
return pStr;
}
int main()
{
char A[]="abcdefg";
int k=2;
cout << LeftRotateString(A,k) << endl;
return 0;
}
在线测试OJ:
http://www.nowcoder.com/books/coding-interviews/12d959b108cb42b1ab72cef4d36af5ec?rp=2
AC代码:
class Solution {
public:
string LeftRotateString(string str, int n) {
int len=str.length();
if(len<=1 || n<=0 || n>=len)
return str;
int pFirstStart=0;
int pFirstEnd=n-1;
int pSecondStart=n;
int pSecondEnd=len-1;
Reverse(str,pFirstStart,pFirstEnd);
Reverse(str,pSecondStart,pSecondEnd);
Reverse(str,pFirstStart,pSecondEnd);
return str;
}
void Reverse(string &str,int pBegin,int pEnd){
char tmp;
while(pBegin<pEnd){
tmp=str[pBegin];
str[pBegin]=str[pEnd];
str[pEnd]=tmp;
pBegin++;
pEnd--;
}
}
};