-
Notifications
You must be signed in to change notification settings - Fork 1
/
java_1_1_1.java
41 lines (36 loc) · 1.05 KB
/
java_1_1_1.java
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
package chapter1;
/**
* 旋转字符串前面的若干字符
* <p>
* 比如abcdef旋转前3个字符到字符串末尾,变成defabc
*/
public class java_1_1_1 {
public static void main(String[] argv) {
char[] str1 = "abcdef".toCharArray();
reverseStr(str1, 3);
System.out.println(str1);
char[] str2 = "".toCharArray();
reverseStr(str2, 0);
System.out.println(str2);
}
//三步旋转法
//1. 将字符串分为两部分,abc,def
//2. 分别原地旋转这两部分,cba,fed
//3. 整个旋转 defabc
public static void reverseStr(char[] str, int count) {
if(str.length == 0) {
return;
}
count %= str.length;
reverseStr(str, 0, count - 1);
reverseStr(str, count, str.length - 1);
reverseStr(str, 0, str.length - 1);
}
private static void reverseStr(char[] str, int from, int to) {
while (from < to) {
char t = str[from];
str[from++] = str[to];
str[to--] = t;
}
}
}