LeetCode:Reverse String II

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"

思路:题目比较简单,主要就是理解清楚剩余字符串的处理就可以了。
 1 void sw(string& s, int b, int e)
 2 {
 3     char t;
 4     while (b<e)
 5     {
 6         t = s[b];
 7         s[b] = s[e];
 8         s[e] = t;
 9         ++b; --e;
10     } 
11 }
12 string reverseStr(string s, int k) 
13 {
14     int len = s.length();
15     int n = len / (2*k);
16     int i =0;
17     for (; i < n; i++)
18         sw(s, i * 2 * k, i * 2 * k + k - 1);
19 
20     if (len - i * 2 * k < k)
21         sw(s, i * 2 * k, len - 1);
22     else
23         sw(s, i * 2 * k, i * 2 * k + k-1);
24         
25     return s;
26 }

 

 

如果你有任何疑问或新的想法,欢迎在下方评论。

posted @ 2017-03-15 12:44  陆小风不写代码  阅读(167)  评论(0编辑  收藏  举报