Given a string and an offset, rotate string by offset. (rotate from left to right)
Given "abcdefg"
.
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
public class Solution { /** * @param str: an array of char * @param offset: an integer * @return: nothing */ public void rotateString(char[] str, int offset) { // write your code here if(str == null || str.length == 0) return; int size = str.length; offset %= size; if(offset == 0) return; for(int i = 0; i < offset; i++) rotate(str); return; } public void rotate(char[] str){ char temp = str[str.length - 1]; for(int i = str.length - 1; i > 0; i--) str[i] = str[i - 1]; str[0] = temp; return; } }
时间: 2024-10-13 11:18:28