[leetcode-541-Reverse String II]

Given a string and an integer k, you need to reverse the first k characters for every 2k characters
counting from the start of the string. If there are less 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 left the other as original.
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]

思路:

以2*k 为一组,每一组前k个字符翻转,然后处理剩余字符。

写出来感觉好啰嗦。。另外简洁的代码看到大神有用stl的reverse的,回头试一下,省不少事儿。

string reverseStr(string s, int k)
     {
         int group = s.size()/(2*k);
         int i = 0;
         for (; i < group;i++)
         {
             for (int j = 0; j < k/2;j++)
             {
                 swap(s[i * 2 * k + j], s[i * 2 * k + k-j-1]);
             }
         }
         int remain = s.size() % (2 * k);
         int end = (remain >= k) ? k : remain ;
         for (int j = 0; j < end/2;j++)
         {
             swap(s[i * 2 * k + j], s[i * 2 * k + end - j - 1]);
         }
         return s;
     }
原文地址:https://www.cnblogs.com/hellowooorld/p/6838426.html