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:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
題目分析
本題給定一字符串s和一個(gè)整數(shù)k,要求每隔k個(gè)字符,將其后的k個(gè)字符逆序排列。如
s = "abcdefg", k = 2
Output: "bacdfeg"
首先將最開始的2個(gè)字符逆序排列,第3,4個(gè)字符順序不變,然后將第4個(gè)字符開始的兩個(gè)字符逆序排列,依次完成剩余字符順序的調(diào)整。
如果最后需要逆序的字符不足k個(gè),則對(duì)剩余的字符逆序即可。
本題可通過如下步驟解決:
(1)若所給k大于等于字符串的長(zhǎng)度,則全部逆序排列返回即可。
(2)最開始的k個(gè)字符逆序.
(3)由于本次需要逆序的最后一個(gè)字符與下一次需要逆序的第一個(gè)字符之間相隔k個(gè)字符,因此本字符的索引順序是2k的整數(shù)倍(從零開始),則該索引為首的連續(xù)k個(gè)字符需要逆序,若不是2k的整數(shù)倍,則不需要逆序,直接復(fù)制原字符串對(duì)應(yīng)位置內(nèi)容即可。
(4)若最后剩余的需要逆序的字符數(shù)不足k個(gè),則只逆序剩余的字符即可。
C語言代碼
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
char* reverseStr(char* strs, int k) {
int len=strlen(strs),i=0,j=0;
char *temp;
temp=(char *)malloc(len+1);
if(k>=len) //k>=len
{
while(strs[i]!='\0')
{
temp[i]=strs[len-i-1];
i++;
}
temp[len]='\0';
return temp;
}
while(strs[i]!='\0')
{
if(i<k) //逆序最開始的k個(gè)字符
{
for(j=0;j<k;j++)
{
temp[j]=strs[k-j-1];
}
i=i+k;
}
else if(i%(2*k)==0) //若是2*k的倍數(shù),則需要逆序接下來的k個(gè)
{
if(len-i+1>k) //接下來的字符數(shù)大于等于k
{
for(j=i;j<i+k;j++)
{
temp[j]=strs[i+k-j+i-1]; //i+j等于本次逆序的最后一個(gè)
}
i=i+k;
}
else //需要逆序字符不足k個(gè)
{
for(j=i;j<len;j++)
{
temp[j]=strs[len-j+i-1];
}
i=len;
}
}
else //不是2*k的倍數(shù)直接復(fù)制原字符串對(duì)應(yīng)位置內(nèi)容
{
temp[i]=strs[i];
i++;
}
}
temp[len]='\0';
return temp;
}
int main()
{
char *strs="abcdefg";
char *string;
int k;
string=reverseStr(strs, 3);
printf("%s",string);
return 0;
}
參考文獻(xiàn)
[1] https://leetcode.com/problems/reverse-string-ii/#/description