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:
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;
}
};
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;
}
};
相关文章推荐
- [leetcode]541. Reverse String II
- [leetcode]: 541. Reverse String II
- LeetCode 541 Reverse String II
- [LeetCode] 344 Reverse String && 541 Reverse String II
- [LeetCode]541. Reverse String II(间隔反转字符串)
- [Leetcode] 541. Reverse String II 解题报告
- LeetCode 541. Reverse String II(C++版)
- LeetCode 541:Reverse String II (c++)
- The Solution to Leetcode 541 Reverse String II
- LeetCode 541. Reverse String II (反转字符串 II)
- LeetCode:541. Reverse String II
- LeetCode-541. Reverse String II (Java)
- leetcode -- 541. Reverse String II 【字符串反转 + 双指针 + 状态记录 + 数组与堆内存】
- Leetcode 541. Reverse String II(Easy)
- LeetCode 541. Reverse String II
- leetcode 541 Reverse String II C++
- leetcode 541. Reverse String II 反转字符串
- LeetCode 541. Reverse String II (字符串翻转)
- Leetcode OJ Contest23 Reverse String II_Leetcode541
- Leetcode #541 Reverse String II