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.
三步反转法。
如果点a是length -1 - offset那个index,反转[0, a],反转[a+1, end],反转[0,end]
细节:
一开始对offset做一个offset = offset % length的处理,可以避免算index越界。 %是求余运算
```java
public class Solution{
public char[] rotateString(char[],int offset){
if(A==null||A.length==0){
return A;
}
offset=offset%A.length;
reverse(A,0,A.length-offset-1);
reverse(A,A.length-offset,A.length-1);
reverse(A,0,A.length-1);
}
private void reverse(char[],int start,int end){
for(int i=start,j=end;i<j;i++;j--){
char tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
}
}