---
title: 'LeetCode 541. Reverse String II'
disqus: hackmd
---
# LeetCode 541. Reverse String II
## Description
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.
## Example
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Input: s = "abcd", k = 2
Output: "bacd"
## Constraints
1 <= s.length <= 10^4^
s consists of only lowercase English letters.
1 <= k <= 10^4^
## Answer
此題因為每隔2k個要轉前k個字元,剩下不足k個的就全轉。一開始先計算長度,若字串長度>k表示能轉k個字元,若長度>2k就往下移動2k,若不夠就往下移動整個剩餘的長度,最後若剩不到k個就再轉剩下的長度即可。
```Cin=
//2022_03_13
void myrev(char *s, int n);
char * reverseStr(char * s, int k){
char *opr = s;
int len = 0;
while(*opr != '\0'){
len = strlen(opr);
if(len > k){
myrev(opr,k);
opr = len > 2*k ? opr + 2*k : opr + len;
}
else{
myrev(opr,len);
opr += len;
}
}
return s;
}
void myrev(char *s, int n){
char *R = s + n - 1;
while(s<R){
char tmp = *s;
*s = *R;
*R = tmp;
s++;
R--;
}
}
```
## Link
https://leetcode.com/problems/reverse-string-ii/
###### tags: `Leetcode`