描述
给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。offset >= 0
str的长度 >= 0
说明
原地旋转意味着需要在函数中更改字符串s。你不需要返回任何东西。
样例
样例 1:
输入:
str = "abcdefg"
offset = 3
输出:
"efgabcd"
解释:注意是原地旋转,即str旋转后为"efgabcd"
样例 2:
输入:
str = "abcdefg"
offset = 0
输出:
"abcdefg"
解释:注意是原地旋转,即str旋转后为"gabcdef"
样例 3:
输入:
str = "abcdefg"
offset = 1
输出:
"gabcdef"
解释:注意是原地旋转,即str旋转后为"gabcdef"
样例 4:
输入:
str = "abcdefg"
offset = 2
输出:
"fgabcde"
解释:注意是原地旋转,即str旋转后为"fgabcde"
样例 5:
输入:
str = "abcdefg"
offset = 10
输出:
"efgabcd"
解释:注意是原地旋转,即str旋转后为"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 (offset==0||str==null||str.length==0) return;
int len = offset%str.length;
char[] temp = new char[len]; // 保存后面的数组
int j = 0;
for (int i = str.length-len; i < str.length ; i++) {
temp[j] = str[i];
j++;
}
int k = str.length - len -1;
for (int i = str.length-1; i >=0 ; i--) {
str[i] = str[k];
k--;
if (k<0) break;
}
for (int i = 0; i < len; i++) {
str[i] = temp[i];
}
}
}
该博客主要讨论了一种简单的字符串原地旋转方法,通过创建临时数组存储部分字符,然后调整原数组完成旋转。示例代码展示了如何处理不同偏移量的情况,并确保字符串在原地进行旋转操作。
283

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



