Categories:

Tags:



Problem

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.

Constraints

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104

Solution

The problem Reverse String II can by solved by reversing the given string for ranges [0, k], [2k, 3k], …, [2nk, (2n+1)k] until (2n+2)k < s.length. When there are characters left and their length is smaller than k, then we can update k to the length of left characters to reverse all of them.

Implementation

class Solution
{
  public:
    string reverseStr(string s, int k)
    {
        int len = s.length();
        for (int i = 0; i < len; i += 2 * k)
        {
            k = min(k, len - i);
            reverse(s.begin() + i, s.begin() + i + k);
        }

        return s;
    }
};