Saturday, December 1, 2018
541. Reverse String II
95.29 %
class Solution {
public String reverseStr(String s, int k) {
if (s == null || s.length() == 0) {
return s;
}
int startIndex = 0;
char[] chars = s.toCharArray();
while (startIndex < s.length()) {
reverse(chars, startIndex, k);
startIndex += 2 * k;
}
return new String(chars);
}
private void reverse(char[] chars, int startIndex, int k) {
int left = startIndex;
int right = Math.min(chars.length - 1, startIndex + k - 1);
swap(left, right, chars);
}
private void swap(int left, int right, char[] chars) {
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment