字符串旋转

题目描述

write description here:给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符’a’和’b’移动到字符串的尾部,
使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//write code here
#include <iostream>
using namespace std;
//解法1,暴力移位法
void leftshiftone(char *s, int n){
char t = s[0];
for (int i = 1; i < n; ++i)
{
/* code */
s[i-1] = s[i];
}
s[n-1] = t;
}
void leftRotateString(char* s, int n, int m){
while(m--) {
/* code */
leftshiftone(s,n);

}
}
void reverseString(char* s, int from, int to){
while(from < to){
char t = s[from];
s[from] = s[to];
s[to] = t;
from++;
to--;
}
}
void reverse(char* s, int n, int m){
m %= n;
reverseString(s, 0, m-1);
reverseString(s, m, n-1);
reverseString(s, 0, n-1);
}
int main(){
char str[6] = "hello";
cout << str <<endl;
leftRotateString(str, 5, 2);
cout << str <<endl;
cout << sizeof(str) <<endl;
reverse(str, 5, 3);
cout << str <<endl;
}
文章目录
  1. 1. 题目描述
|