Description
https://leetcode.com/problems/reverse-string-ii/
给定一个字符串和一个整数k,需要反转从字符串开头算起的每2k个字符的前k个字符。
如果剩下少于k个字符,则反转所有字符;
如果小于2k但大于或等于k个字符,则反转前k个字符。
Solving Ideas
https://leetcode.com/problems/reverse-string-ii/solution/
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Solution
class Solution {
public String reverseStr(String s, int k) {
if (s == null || s.length() < 1 || k < 1) return s;
char[] res = s.toCharArray();
for (int i = 0; i < s.length(); i += 2 * k) {
int left = i, right = Math.min(i + k - 1, s.length() - 1);
while (left < right) {
char tmp = res[left];
res[left++] = res[right];
res[right--] = tmp;
}
}
return new String(res);
}
}