-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution001.java
47 lines (39 loc) · 1.09 KB
/
Solution001.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
42
43
44
45
46
47
package algorithm.tmop;
/**
* @author: mayuan
* @desc:
* 时间复杂度: O(n)
* 空间复杂度: O(1)
* @date: 2018/11/19
*/
public class Solution001 {
public static void main(String[] args) {
final char[] array = {'a', 'b', 'c', 'd', 'e', 'f'};
final int n = 3;
for (char c : array) {
System.out.print(c + " ");
}
System.out.println();
leftRotateString(array, n);
for (char c : array) {
System.out.print(c + " ");
}
System.out.println();
}
public static void leftRotateString(char[] array, int n) {
// 如果向左移动大于 array.length, 则进行取余
n %= array.length;
reverseString(array, 0, n - 1);
reverseString(array, n, array.length - 1);
reverseString(array, 0, array.length - 1);
}
public static void reverseString(char[] array, int from, int to) {
while (from < to) {
char tmp = array[from];
array[from] = array[to];
array[to] = tmp;
++from;
--to;
}
}
}