Given a string and an offset, rotate string by offset. (rotate from left to right)
Have you met this question in a real interview?
Yes
Example
Given "abcdefg"
for offset=0, return "abcdefg"
for offset=1, return "gabcdef"
for offset=2, return "fgabcde"
for offset=3, return "efgabcd"
...
public class Solution { /* * param A: A string * param offset: Rotate string with offset. * return: Rotated string. */ public char[] rotateString(char[] A, int offset) { // wirte your code here if (A==null || A.length == 0) return new char[0]; int len = A.length; offset = offset % len; String str = new String(A); if (offset == 0) return str.toCharArray(); String first = str.substring(0,len - offset); String second = str.substring(len - offset); String res = second+first; return res.toCharArray(); } };
public class Solution { /* * param A: A string * param offset: Rotate string with offset. * return: Rotated string. */ public char[] rotateString(char[] A, int offset) { // wirte your code here if (A==null || A.length == 0) return new char[0]; int len = A.length; offset = offset % len; reverse(A,0,len-offset-1); reverse(A,len-offset,len-1); reverse(A,0,len-1); return A; } public void reverse(char[] A, int start, int end){ while(start<end){ char temp = A[start]; A[start++] = A[end]; A[end--] = temp; } } };