# Java Concise Solution

• ``````public class Solution {
public String reverseStr(String s, int k) {
char[] arr = s.toCharArray();
int n = arr.length;
int i = 0;
while(i < n) {
int j = Math.min(i + k - 1, n - 1);
swap(arr, i, j);
i += 2 * k;
}
return String.valueOf(arr);
}
private void swap(char[] arr, int l, int r) {
while (l < r) {
char temp = arr[l];
arr[l++] = arr[r];
arr[r--] = temp;
}
}
}
``````

• Same idea. Thanks for sharing!

``````    public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i += 2 * k) {
rev(ch, i, i + k);
}
return String.valueOf(ch);
}

private void rev(char[] ch, int i, int j) {
j = Math.min(ch.length, j) - 1;
for (; i < j; i++, j--) {
char tmp = ch[i];
ch[i] = ch[j];
ch[j] = tmp;
}
}
``````

• Excellent solution

• This post is deleted!

• @MrHare k will in the range [1, 10000]

• @sheva Brilliant solution !

• My code is more complex. In your code, using int j = Math.min(i + k - 1, n - 1) and just swap the specific positions of array is very tricky which can avoid many end conditions determination. Thanks for sharing!

``````public class Solution {
public String reverseStr(String s, int k) {
StringBuilder sb = new StringBuilder();
int i = 0;
while(i<s.length()){
if((i+2*k >s.length()) && (i+k < s.length())){
sb.append(reverse(s.substring(i,i+k)));
sb.append(s.substring(i+k,s.length()));
break;
}
if(i+k >= s.length()){
sb.append(reverse(s.substring(i,s.length())));
break;
}
sb.append(reverse(s.substring(i,i+k)));
i+=k;
sb.append(s.substring(i,i+k));
i+=k;
}
return sb.toString();
}
public String reverse(String s){
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
}
``````

• @sheva yes,the `int j = Math.min(i + k - 1, n - 1);` is necessary and good,I enjoy your solution :]

• I think you initialize a new StringBuilder too many times which will increase your cost. Every time when you want to reverse a string, you will create a stringbuilder

• ``````    public String reverseStr(String s, int k) {
if(s == null || s.isEmpty()){return s;}
StringBuilder sb = new StringBuilder();
boolean reverse = true;
for(int i = 0; i < s.length(); i = i + k, reverse = !reverse){
int end = (i + k) < s.length() ? (i + k - 1) : s.length()-1;
if(reverse)
for(int j = end; j >= i; j--){sb.append(s.charAt(j));} // Copy in reverse
else
for(int j = i; j <= end; j++){sb.append(s.charAt(j));} // Copy as it is
}
return sb.toString();
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.