1.题目描述
2.题解
i.我的解法
ii.使用整体反转+局部反转
具体步骤为:
- 反转区间为前n的子串
- 反转区间为n到末尾的子串
- 反转整个字符串
3.代码示例
i.我的解法
class Solution {
public String reverseLeftWords(String s, int n) {
char[] result=s.toCharArray();
int length=result.length;
int left=0,right=1;//定义双指针
char temp;
for(int i=0;i<n;i++){
temp=result[0];//取第一个元素(参与左旋),一共取n次
//后一位元素覆盖到前一位元素
while(right<length) result[left++]=result[right++];
//一次循环结束要将指针还原好进行下一次覆盖操作
left=0;
right=1;
result[length-1]=temp;//把取到的参与左旋的元素放到最后
}
return String.valueOf(result);
}
}
ii. 使用整体反转+局部反转
class Solution {
public String reverseLeftWords(String s, int n) {
char[] chars = s.toCharArray();
reverse(chars, 0, chars.length - 1);
reverse(chars, 0, chars.length - 1 - n);
reverse(chars, chars.length - n, chars.length - 1);
return new String(chars);
}
public void reverse(char[] chars, int left, int right) {
while (left < right) {
chars[left] ^= chars[right];
chars[right] ^= chars[left];
chars[left] ^= chars[right];
left++;
right--;
}
}