LeetCode 541: Reverse String II
LeetCode 541 Solution Explanation
Explanation
To solve this problem, we can iterate over the string in steps of 2k, and for each group of k characters, we reverse the first k characters. If the remaining characters are less than k but greater than 0, we reverse all of them. We can achieve this by swapping characters from the start and end of the group of k characters until we reach the middle.
Time Complexity: O(n) where n is the length of the string s. Space Complexity: O(1) as we are not using any extra space other than a few variables.
LeetCode 541 Solutions in Java, C++, Python
class Solution {
public String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
for (int i = 0; i < s.length(); i += 2*k) {
int start = i;
int end = Math.min(i + k - 1, s.length() - 1);
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
return new String(chars);
}
}
Interactive Code Editor for LeetCode 541
Improve Your LeetCode 541 Solution
Use the editor below to refine the provided solution for LeetCode 541. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...