LeetCode541 Reverse String II

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

Restrictions:

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

样例

1
2
Input: s = "abcdefg", k = 2
Output: "bacdfeg"

思路

给一个字符串和一个整数$k$,需要每$2k$个字符就把前$k$个字符翻转,如果少于$k$个字符就都翻转,如果多等于$k$个而于少于$2k$个字符,就翻转前$k$个而剩下的不变。

按题意模拟一下即可…

代码

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
void rev(string& s, int l, int r) {
while (l < r) swap(s[l++], s[r--]);
}
string reverseStr(string s, int k) {
int siz = s.size();
for (int i = 0; i < siz; i += 2*k) rev(s, i, min(i + k - 1, siz - 1));
return s;
}
};
分享到 评论