1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public String reverseStr(String s, int k) { char[] chars = s.toCharArray(); for (int startIndex = 0; startIndex < chars.length; startIndex += 2 * k) { reverse(chars, startIndex, Math.min(startIndex + k - 1, chars.length - 1)); }
return new String(chars); }
private void reverse(char[] chars, int left, int right) { while (left < right) { swap(chars, left++, right--); } }
private void swap(char[] chars, int i, int j) { char tmp = chars[i]; chars[i] = chars[j]; chars[j] = tmp; } }
|