LeetCode-541. Reverse String II


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和一个整数k,要求每隔k个字符,将其后的k个字符逆序排列。如

s = "abcdefg", k = 2
Output: "bacdfeg"

首先将最开始的2个字符逆序排列,第3,4个字符顺序不变,然后将第4个字符开始的两个字符逆序排列,依次完成剩余字符顺序的调整。
如果最后需要逆序的字符不足k个,则对剩余的字符逆序即可。

本题可通过如下步骤解决:
(1)若所给k大于等于字符串的长度,则全部逆序排列返回即可。
(2)最开始的k个字符逆序.
(3)由于本次需要逆序的最后一个字符与下一次需要逆序的第一个字符之间相隔k个字符,因此本字符的索引顺序是2k的整数倍(从零开始),则该索引为首的连续k个字符需要逆序,若不是2k的整数倍,则不需要逆序,直接复制原字符串对应位置内容即可。
(4)若最后剩余的需要逆序的字符数不足k个,则只逆序剩余的字符即可。

C语言代码

#include 
#include 
#include 
#include  


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(ik)             //接下来的字符数大于等于k
                {   
                    for(j=i;j

参考文献
[1] https://leetcode.com/problems/reverse-string-ii/#/description

你可能感兴趣的:(LeetCode-541. Reverse String II)