8. Rotate String

时间:2023-03-09 14:21:25
8. Rotate String

8. Rotate String

Description

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.

三步旋转法:

1.将末尾offset个字符旋转
2.将 0- (length-ofset)字符 旋转
3.将全部的字符旋转
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(offset == 0 )
return;
if(str.length == 0)
return;
for(int i = 0; i < offset%str.length; i++)
{
char temp = str[str.length-1];
int j = str.length-2;
while(j >= 0)
{
str[j+1] = str[j];
j--; }
str[0] = temp;
}
}
}
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.length==0){
return;
}
if(offset==0){
return;
}else if(offset%str.length==0){
return;
}else{
offset=offset%str.length;
int[] temp=new int[offset];
for(int i=str.length-offset;i<str.length;i++){
temp[i-str.length+offset]=str[i];
}
/*for(int j=0;j<temp.length;j++){
System.out.println((char)temp[j]);
}*/
for(int i=str.length-offset-1;i>=0;i--){
str[i+offset]=str[i];
}
for(int i=0;i<offset;i++){
str[i]=(char)temp[i];
}
}
}
}
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)