dcddc

西米大人的博客

0%

旋转字符串

题目描述

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)。
例如,对于字符串abcdefg,offset=1 => “gabcdef”

思路

  • k(偏移量)次移位法
    • 对于偏移量k,每次从左到右移位一次,移动k次即可
    • 注意,每次移位先保存最左边的char,然后从右二开始从左到右一个一个移位
  • 对称变换法
    • 对于一个字符串,如果将其分成两部分,对于每一部分均对称变换,然后再对合起来的字符串对称变换,字符串的相对位置不变。
    • 所以对于偏移量为k,其效果是将最右边的k位移到左边。考虑将最右边的k位对称变换,将左边开始的n-k位对称变换,之后再对合起来的字符串对称变换即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void rotateString(char[] str, int offset) {
if(str.length == 0) return;
offset = offset % str.length;
mysubRotate(str, 0, str.length-offset-1);
mysubRotate(str, str.length-offset, str.length-1);
mysubRotate(str, 0, str.length-1);
}

private void mysubRotate(char[] str, int start, int end) {
while(start < end) {
char tmp = str[start];
str[start] = str[end];
str[end] = tmp;
start++;
end--;
}
}

考差点

  • 字符串处理