LC题解-左旋转字符串

  • 反转区间为前n的子串

  • 反转区间为n到末尾的子串

  • 反转整个字符串

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
class Solution {
public String reverseLeftWords(String s, int n) {
char[] sc = s.toCharArray();

// 前 sc.length - n 翻转
int l = 0;
int r = n - 1;
while(l < r) {
char t = sc[l];
sc[l++] = sc[r];
sc[r--] = t;
}

// n 到 结尾翻转
l = n;
r = sc.length - 1;
while(l < r) {
char t = sc[l];
sc[l++] = sc[r];
sc[r--] = t;
}

// 全部翻转
l = 0;
r = sc.length - 1;
while(l < r) {
char t = sc[l];
sc[l++] = sc[r];
sc[r--] = t;
}

return new String(sc);
}
}