541 Reverse String II Reverse String II

Given a string and an integer k, you need to reverse the first k characters of every 2k characters from the beginning of the string. If there are less than k characters remaining, reverse all that remains. If there are less than 2k but greater than or equal to k characters, reverse the first k characters and leave the rest as-is.
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Requirements:
    1. The string contains only lowercase English letters.
    2. The length and k of the given string are in the range [1, 10000].
See: https://leetcode.com/problems/reverse-string-ii/description/

C++:

class Solution {
public:
    string reverseStr(string s, int k)
    {
        int n = s.size(), cnt = n / k;
        for (int i = 0; i <= cnt; ++i)
        {
            if (i % 2 == 0)
            {
                if (i * k + k < n)
                {
                    reverse(s.begin() + i * k, s.begin() + i * k + k);
                }
                else
                {
                    reverse(s.begin() + i * k, s.end());
                }
            }
        }
        return s;
    }
};

 Reference: http://www.cnblogs.com/grandyang/p/6583004.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324762787&siteId=291194637