LeetCode 541: Reverse String II

Two PointersString

Problem Description

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.

Solutions

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);
    }
}

Loading editor...