541. 反转字符串 II - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/reverse-string-ii/先把2k的整倍数之外的元素(剩余部分)处理了,之后留下的2k整倍数个就很好处理了。
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
if(s.length()%(2*k)<k){//剩余少于k,全部反转
int begin = s.length()-s.length()%(2*k);
int end = s.length()-1;
reverseChars(chars,begin,end);
}else if(s.length()%(2*k)>=k){//剩余大于等于k,反转k个
int begin = s.length()-s.length()%(2*k);
int end = begin+k-1;
reverseChars(chars,begin,end);
}
int loop = s.length()/(2*k);//长度除以2k就是需要反转的次数
for (int i=0;i<loop;i++){
reverseChars(chars,i*2*k,i*2*k+k-1);
}
return new String(chars);
}
void reverseChars(char[] chars,int begin,int end){
char temp;
while (begin<end){
temp = chars[begin];
chars[begin] = chars[end];
chars[end] = temp;
begin++;
end--;
}
}
}
还有一种更简洁的方法,直接上代码
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for(int i=0;i< chars.length;i+=2*k){
int begin = i;
int end = Math.min(chars.length-1,begin+k-1);//最多翻转k个字符,所以end就是数组长度-1与begin往后k-1的最小值
reverseChars(chars,begin,end);
}
return new String(chars);
}
static void reverseChars(char[] chars,int begin,int end){
char temp;
while (begin<end){
temp = chars[begin];
chars[begin] = chars[end];
chars[end] = temp;
begin++;
end--;
}
}
public void main(String[] args) {
char[] chars = {'a','b','c'};
reverseChars(chars,0,2);
System.out.println(chars);
}
}