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

LeetCode 541. Reverse String II

2017-08-09 10:45 417 查看

541. Reverse String II


4000
Description

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:
1. The string consists of lower English letters only.
2. Length of the given string and k will in the range [1, 10000]


Solution

题意即给定一个字符串和一个正整数k,要求每隔2k个位置,将字符串k个长度的子串颠倒。如果长度不满足2k或k,则以最大长度为计。

利用循环控制处理起始位置,然后用while循环处理颠倒,中间注意处理k、2k过大的情况。代码如下。

char* reverseStr(char* s, int k) {
int len = strlen(s);
for (int i = 0;i < len;i+=2*k) {
int l = i,r = i + k - 1;
if (r >= len) r = len - 1;
while (l < r) {
char temp = s[l];
s[l] = s[r];
s[r] = temp;
l++;
r--;
}
}
return s;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 leetcode