CodingInterview-左旋转字符串

如果模左移动直接移动字符串的话效率太低,可以通过三次字符串旋转完成。解法如下,注意判断异常情况和边界值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string LeftRotateString(string str, int n) {
int strlen=str.length();
if(n==0 || strlen==0 || n==strlen || n>strlen) return str;
this->rotateString(&str,n);
this->rotateString(&str,strlen);
this->rotateString(&str,strlen-n);
return str;
}
void rotateString(string* str,int end){
for(int i=0;i<end/2;i++){
char temp=(*str)[i];
(*str)[i]=(*str)[end-i-1];
(*str)[end-i-1]=temp;
}
}
};