第一次写比较笨拙, 嵌套使用了stringbuilder, subsubstring和reverse
public class Solution {
public String reverseStr(String s, int k) {
StringBuilder sb = new StringBuilder(s);
StringBuilder ans = new StringBuilder();
while(sb.length()>2*k){
ans.append(new StringBuilder(sb.substring(0,k)).reverse());
ans.append(sb.substring(k,2*k));
sb = new StringBuilder(sb.substring(2*k));
}
if(sb.length()<k){
ans.append(sb.reverse());
}
else{
ans.append(new StringBuilder(sb.substring(0,k)).reverse());
ans.append(sb.substring(k));
}
return ans.toString();
}
}
更简单的方式是写一个swap函数在原string上做操作. 参考论坛里的代码
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;
}
}
}