一、题目

Given a string and an offset, rotate string by offset. (rotate from left to right)

Example

Given "abcdefg".

offset=0 => “abcdefg”
offset=1 => “gabcdef”
offset=2 => “fgabcde”
offset=3 => “efgabcd”

Challenge

Rotate in-place with O(1) extra memory.

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

二、解题思路

常见的翻转法应用题,仔细观察规律可知翻转的分割点在从数组末尾数起的offset位置。先翻转前半部分,随后翻转后半部分,最后整体翻转。

三、解题代码

  1. public class Solution {
  2. /*
  3. * param A: A string
  4. * param offset: Rotate string with offset.
  5. * return: Rotated string.
  6. */
  7. public char[] rotateString(char[] A, int offset) {
  8. if (A == null || A.length == 0) {
  9. return A;
  10. }
  11. int len = A.length;
  12. offset %= len;
  13. reverse(A, 0, len - offset - 1);
  14. reverse(A, len - offset, len - 1);
  15. reverse(A, 0, len - 1);
  16. return A;
  17. }
  18. private void reverse(char[] str, int start, int end) {
  19. while (start < end) {
  20. char temp = str[start];
  21. str[start] = str[end];
  22. str[end] = temp;
  23. start++;
  24. end--;
  25. }
  26. }
  27. }