算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 反转字符串 II,我们先来看题面:
https://leetcode-cn.com/problems/reverse-string-ii/
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer 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 leave the other as original.
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
示例
示例 1:
输入:s = "abcdefg", k = 2
输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2
输出:"bacd"
解题
https://www.cnblogs.com/wltree/p/15523126.html
思路:首先需要找到大区间,然后需要找到大区间里面需要反转的小区间。通过题目描述不难发现,每次大区间的其实位置都会间隔 2k 。大区间的起始位置也是反转小区间的起始位置,接着找出反转小区间的终点位置,终点位置有两种情况:一是能取到 k 个元素,二是取不到 k 个元素。
class Solution {
public:
string reverseStr(string s, int k) {
// i 每次移动 2 * k
for (int i = 0; i < s.size(); i = i + 2 * k) {
// left 和 right 定义需要反转的区间
int left = i;
int right;
//判断要交换的区间里面还有没有 k 个元素
if (i + k - 1 >= s.size()) {
right = s.size() - 1;
} else {
right = i + k - 1;
}
//将区间内的元素进行交换
while (left < right) {
int temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
return s;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: