LintCode-Rotate String
Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Given "abcdefg"
for offset=0, return "abcdefg"
for offset=1, return "gabcdef"
for offset=2, return "fgabcde"
for offset=3, return "efgabcd"
Solution:
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.length==0) return A; 9 offset = offset % A.length; 10 if (offset == 0) return A; 11 int len = A.length; 12 //Store the rotated char in buffer. 13 char[] buff = new char[offset]; 14 for (int i=len-offset;i<len;i++) 15 buff[i-len+offset] = A[i]; 16 17 //Move the left chars to right. 18 for (int i=len-offset-1;i>=0;i--) 19 A[i+offset] = A[i]; 20 21 //Put the chars in buff into array. 22 for (int i=0;i<offset;i++) 23 A[i] = buff[i]; 24 25 return A; 26 } 27 };