描述
给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。
样例 1:
输入: str=“abcdefg”, offset = 3
输出: str = “efgabcd”
样例解释: 注意是原地旋转,即str旋转后为"efgabcd"
样例 2:
输入: str=“abcdefg”, offset = 0
输出: str = “abcdefg”
样例解释: 注意是原地旋转,即str旋转后为"abcdefg"
样例 3:
输入: str=“abcdefg”, offset = 1
输出: str = “gabcdef”
样例解释: 注意是原地旋转,即str旋转后为"gabcdef"
样例 4:
输入: str=“abcdefg”, offset =2
输出: str = “fgabcde”
样例解释: 注意是原地旋转,即str旋转后为"fgabcde"
样例 5:
输入: str=“abcdefg”, offset = 10
输出: str = “efgabcd”
样例解释: 注意是原地旋转,即str旋转后为"efgabcd"
思路:
本来想着就是普通string api就能解决,后来想到了更好的~两个一样的字符串连起来,然后往后读一个字符串的长度就好了,第一个写了代码,第二个懒得写了。。
我的答案:
public void rotateString(char[] str, int offset) {
// write your code here
if(str.length == 0 || offset == 0){
return;
}
offset = offset%str.length;
for(int i = 0;i<offset; i++){
char temp = str[str.length-1];
for(int j = str.length-1;j>0;j–){
str[j] = str[j-1];
}
str[0] = temp;
}
}