-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathReverseStringII.java
More file actions
34 lines (34 loc) · 901 Bytes
/
ReverseStringII.java
File metadata and controls
34 lines (34 loc) · 901 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package io.ziheng.string.leetcode;
/**
* LeetCode 541. Reverse String II
* https://leetcode.com/problems/reverse-string-ii/
*/
public class ReverseStringII {
public String reverseStr(String s, int k) {
if (s == null || s.length() < 2 || k < 0) {
return s;
}
char[] charArray = s.toCharArray();
int i = 0;
int n = charArray.length;
while (i < n) {
int end = Math.min(i + k - 1, n - 1);
reverseStr0(charArray, i, end);
i += 2 * k;
}
return String.valueOf(charArray);
}
private void reverseStr0(char[] s, int left, int right) {
while (left < right) {
swap(s, left, right);
left++;
right--;
}
}
private void swap(char[] s, int i, int j) {
char c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* EOF */