Leetcode 541 Solution

This article provides solution to leetcode question 541 (reverse-string-ii)

https://leetcode.com/problems/reverse-string-ii

Solution

class Solution {
public:
    string reverseStr(string s, int k) {
        int l = 0;
        int r = min(k - 1, (int)s.size() - 1);

        while (l < s.size())
        {
            int last_left = l;
            while (l < r)
                swap(s[l++], s[r--]);

            if (last_left + 2 * k >= s.size())
                break;

            l = last_left + 2 * k;
            r = min(l + k - 1, (int)s.size() - 1);
        }

        return s;
    }
};