796.Rotate-String

796. Rotate String

题目地址

http://www.lintcode.com/problem/rotate-string/

http://www.jiuzhang.com/solutions/rotate-string/

题目描述

Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right).

Example
Input: str="abcdefg", offset = 3
Output: str = "efgabcd"    
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".

代码

public class Solution {
    public void rorateString(char[] str, int offset) {
    if (str == null || str.length == 0)    return;

    offset = offset % str.length;
    reverse(str, 0, str.length - offset - 1);
    reverse(str, str.length - offset, str.length - 1);
    reverse(str, 0, str.length - 1);

  }

  private void reverse(char[] str, int start, int end) {
    for (int i = start, j = end; i < j; i++, j--) {
      char temp = str[i];
      str[i] = str[j];
      str[j] = temp;
    }
  }

}

Last updated