您的位置:首页 > 编程语言 > C语言/C++

LeetCode 541:Reverse String II (c++)

2017-06-21 09:41 363 查看
一:题目

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]
二:解题分析

根据题目的描述,有以下几种情况:

1.字符串为空,直接反转

2.字符串长度<k,将所有反转

3.字符串长度>=k,<=2k,将前k个字符反转

4.字符串长度>2k,将前k个字符反转

三:代码实现

class Solution {
public:
string reverseStr(string s, int k) {
//几种情况
//1.字符串为空,直接反转
//2.字符串长度<k,将所有反转
//3.字符串长度>=k,<=2k,将前k个字符反转
//4.字符串长度>2k,将前k个字符反转

//1.字符串为空,直接反转
if(s.empty())
return s;

//需要记录,未反转字符串的长度,开始位置
int currentLength=s.length();
int begin=0;
string reverseString;
int i;

while(currentLength>0){
//2.字符串长度<k,将所有反转
if(currentLength<k){
for(i=s.length()-1;i>=begin;i--)
reverseString+=s[i];
break;
}
//3.字符串长度>=k,<=2k,将前k个字符反转
if(currentLength>=k && currentLength<=2*k){
for(i=begin+k-1;i>=begin;i--)
reverseString+=s[i];
for(i=begin+k;i<=begin+2*k-1;i++)
reverseString+=s[i];
break;
}
//4.字符串长度>2k,将前k个字符反转
if(currentLength>2*k){
for(i=begin+k-1;i>=begin;i--)
reverseString+=s[i];
for(i=begin+k;i<=begin+2*k-1;i++)
reverseString+=s[i];
currentLength-=2*k;
begin+=2*k;

}

}

return reverseString;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息