Rotate String
Description
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”;
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 ;
}
offset = offset % str.length ;
if(offset == 0){
return ;
}
int len = str.length -1 ;
char[] str1 = new char[len] ;
char[] str2 = new char[len] ;
for(int i = 0 ; i < len-offset+1 ; i++){
str1[i] = str[i] ;
}
int count = 0 ;
for(int j = len-offset+1 ; j <= len ; j++){
str2[count] = str[j] ;
count++ ;
}
for(int i = 0 ; i < str2.length ; i++){
str[i] = str2[i] ;
}
int count1 = 0 ;
for(int j = offset ; j <= len ; j++){
str[j] = str1[count1] ;
count1++ ;
}
}
}
这篇文章介绍了如何使用C++实现字符串的旋转功能,通过给定字符数组和偏移量,实现在原地进行左向右的旋转操作。代码示例详细解释了旋转过程,并针对输入边界条件进行了处理。
16万+

被折叠的 条评论
为什么被折叠?



