1. 程式人生 > >[leetcode-541-Reverse String II]

[leetcode-541-Reverse String II]

string cnblogs div tco ever 大神 turn letter 字符

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

[leetcode-541-Reverse String II]