您的位置:首页 > 其它

LeetCode 541 Reverse String II

2017-07-31 09:00 316 查看
题目:

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]
题目链接
题意:

给一个字符串和一个整型数k,需要每2k个字符反转前k个,假如字符串长度不足k,则全部反转,假如字符串长度大于k小于2k,则反转前k个字符,剩余的字符保持原样。

例如 s = “abcdefg” k = 2

第一次反转:选2k个字符“abcd”,反转前k个“bacd”

第二次反转:选2k个字符,但余下的不足2k个,但大于k个,所以只把前k个全部反转“feg”

得到答案“bacdfeg”

在实现的时候,每次只需要拿出2k个字符,翻转后在替换回去即可,注意判断不足的情况。

代码如下:

class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0; i < s.length(); i += 2*k) {
string temp = s.substr(i, i+k < s.length() ? k : s.length()-i);
reverse(temp.begin(), temp.end());
s.replace(i, i+k < s.length() ? k : s.length()-i, temp);
}
return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: