左旋转字符串

Problem description

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。

Examples

1
2
3
Example 1:
Input:abcdefg, 2
Output:cdefgab

Solution

K对length进行取余,减少计算量。

  1. 先旋转前k个字符串
  2. 再旋转剩余字符串
  3. 全体旋转一次

Code

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
 void reverse(char[] s, int low, int high) {

if (s == null || s.length <= 1 || low > high) {
return;
}
char c;
while (low < high) {
c = s[low];
s[low] = s[high];
s[high] = c;
low++;
high--;
}
}
private void leftRotateString(char[] str, int k) {
if (str == null || str.length <= 1) {
return;
}

k %= str.length;

reverse(str, 0, k - 1);
reverse(str, k, str.length - 1);
reverse(str, 0, str.length - 1);
}
文章目录
  1. 1. Problem description
    1. 1.1. 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。
  2. 2. Examples
  3. 3. Solution
  4. 4. Code
|