[LintCode] Rotate String
public void rotateString(char[] str, int offset) { // write your code here if(offset == 0 || str.length == 0) return; offset = offset % str.length; reverse(str, 0, str.length - 1 - offset); reverse(str, str.length - offset, str.length - 1); reverse(str, 0 , str.length - 1); } public void reverse(char[] c, int i, int j) { while(i < j) { swap(c,i,j); i++; j--; } } public void swap(char[] c, int i, int j) { char t = c[i]; c[i] = c[j]; c[j] = t; }
Leave A Comment