Leetcode 541. Reverse String II
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer than k
characters left, reverse all of them. If there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters and leave the other as original.
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Input: s = "abcd", k = 2
Output: "bacd"
Q: Are there any constraints on the value of k
or the length of string s
?
A: The length of s
will be between 1 and 10000. k
will be a positive integer.
Q: What are the characters contained in the string s
?
A: The string s
consists of lower English letters only.
s
in chunks of 2k
.k
characters.2k - k
characters as they are.k
characters left, simply reverse them.Let’s implement this now:
public class Solution {
public String reverseStr(String s, int k) {
char[] arr = s.toCharArray();
for (int start = 0; start < arr.length; start += 2 * k) {
int i = start, j = Math.min(start + k - 1, arr.length - 1);
while (i < j) {
char temp = arr[i];
arr[i++] = arr[j];
arr[j--] = temp;
}
}
return new String(arr);
}
// Main method for testing
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.reverseStr("abcdefg", 2)); // Output: "bacdfeg"
System.out.println(sol.reverseStr("abcd", 2)); // Output: "bacd"
}
}
s
to a character array arr
to allow in-place modifications.2 * k
.2 * k
:
k
characters using two pointers technique.i
meets j
to ensure the segment is reversed properly.The time complexity of this solution is (O(n)), where (n) is the length of the string s
:
k
characters) is an (O(k)) operation, but considering it happens within the loop, the overall time complexity remains linear in terms of string length.The space complexity is (O(n)) only due to the conversion of the string to a character array, which is necessary to perform in-place modification in Java. Apart from this, the algorithm uses a constant amount of extra space for variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?