您的位置:首页 > 其它

LeetCode 541. Reverse String II (字符串翻转)

2017-05-31 22:36 369 查看
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]
输入字符串s和正整数k,对于每2k个字母,将其中前k个字母翻转。最后如果剩余字母少于k个,则将其全部翻转;若多于k个,则将前k个翻转,其余不变。

思路:利用void reverse(str.begin(),str.end())函数直接原位翻转,若要翻转到其他变量,可使用str2.assign(str.rbegin(), str.rend())函数。

string reverseStr(string s, int k) {
int left = s.size()%(2*k);
int i;

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