Given a string of char array and an offset, rotate the string by offset in place
. (from left to right).
In different languages, str
will be given in different ways. For example, the string "abc"
will be given in following ways:
- Java: char[] str = {'a', 'b', 'c'};
- Python:str = ['a', 'b', 'c']
- C++:string str = "abc";
offset >= 0
the length of str >= 0In place
means you should change strings in the function. You don't return anything.
Example 1:
Input:
str = ""abcdefg"
offset = 3
Output:
"efgabcd"
Explanation:
Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".
Example 2:
Input:
str = ""abcdefg"
offset = 0
Output:
"abcdefg"
Explanation:
Note that it is rotated in place, that is, after str is rotated, it becomes "abcdefg".
Example 3:
Input:
str = ""abcdefg"
offset = 1
Output:
"gabcdef"
Explanation:
Note that it is rotated in place, that is, after str is rotated, it becomes "gabcdef".
Example 4:
Input:
str = ""abcdefg"
offset = 2
Output:
"fgabcde"
Explanation:
Note that it is rotated in place, that is, after str is rotated, it becomes "fgabcde".
Example 5:
Input:
str = ""abcdefg"
offset = 10
Output:
"efgabcd"
Explanation:
Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".
public void rotateString(char[] chars, int offset){ if(chars.length == 0) return null offset = offset % chars.length; reverse(chars, 0, chars.length-1); reverse(chars, 0, offset-1); reverse(chars, offset, chars.length-1); return ; } private void reverse(char[] arr, int start, int end) { while(start < end) { char temp = arr[start]; arr[start++] = arr[end]; arr[end--] = temp; } }
reverse的一百种用法