Easy-50

来源:互联网 发布:js ajax进行post请求 编辑:程序博客网 时间:2024/05/01 11:37

leetcode        541. Reverse String II          

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 = 2Output: "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]

AC:

void res(char* s,int start,int end)
{
    int len=end+start;
    len=len/2;
    for(int i=start;i<=len;i++)
    {
        int c=s[i];
        s[i]=s[end-i+start];
        s[end-i+start]=c;
    }
}

char* reverseStr(char* s, int k) {
    int len=strlen(s);
    int count=len/(2*k);
    for(int i=1;i<=count;i++)
    {
        res(s,2*k*i-2*k,2*k*i-k-1);
    }
    int re=len%(2*k);
    if(re!=0)
    {
        if(re>=k)
        res(s,count*(2*k),(k-1)+count*(2*k));
        else
        res(s,count*(2*k),(re-1)+count*(2*k));
    }
    return s;
}

tips: 注意下标与长度之间的转换!!!

原创粉丝点击