字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = “abcdefg”, k = 2
输出: “cdefgab”
示例 2:
输入: s = “lrloseumgh”, k = 6
输出: “umghlrlose”
局部反转+整体反转
反转整个字符串
反转区间为前n的子串
反转区间为n到末尾的子串
代码
class Solution {
public String reverseLeftWords(String s, int n) {
//1、获取字符串长度
int length=s.length();
//2、字符串转成数组
char[] chars=s.toCharArray();
// 3、把字符数组的所有字符反转
//即a b c d e f g
//变成了g f e d c b a
reserve(chars,0,length-1);
//4、再反转前length - n个字符
//即g f e d c b a
//变成了c d e f g b a
reserve(chars,0,length-n-1);
// 5、再反转剩余的字符
//即c d e f g b a
//变成了c d e f g a b
reserve(chars,length-n,length-1);
//返回字符串
return new String(chars);
}
public void reserve(char[] chars,int start,int end){
while(start<end){
char temp=chars[end];
chars[end]=chars[start];
chars[start]=temp;
start++;
end--;
}
}
}