首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-541-Reverse String II

leetcode-541-Reverse String II

作者头像
chenjx85
发布2018-05-22 16:30:53
3090
发布2018-05-22 16:30:53
举报

题目描述:

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]

要完成的函数:

string reverseStr(string s, int k)

说明:

1、这道题目看懂题意之后很容易做。给定一个字符串s和一个数字k,反转字符串前2k位中的k位。比如abcdefg,k=2,也就是反转前4位abcd中的前两位ab,反转结果为bacd。

当我们处理到字符串末尾的时候,不一定都能找到刚好有2k位的。所以这个时候如果有小于2k位但是大于等于k位的,反转前面k位,后面不用变化。如果小于k位,那么反转剩下的所有字母。

2、我们把上述条件转化一下,构造如下代码(附解释):

    string reverseStr(string s, int k) 
    {
        int i=0,s1=s.size(),j,t1;//i用来记录起始位置
        char t;//反转过程中的临时变量
        while(i<s1)
        {
            if(i+2*k-1<s1)//正常情况
            {
                t1=i+2*k;//记录处理完2k个字母之后下一个字母的位置
                j=i+k-1;//要处理k个字母,j记录末尾位置
                while(i<j)//反转
                {
                    t=s[i];
                    s[i]=s[j];
                    s[j]=t;
                    i++;
                    j--;
                }
                i=t1;//i更新到下一个要处理的字母位置
            }
            else if(i+2*k-1>=s1&&i+k-1<s1)//特殊情况,<2k&&>=k
            {
                j=i+k-1;
                while(i<j)
                {
                    t=s[i];
                    s[i]=s[j];
                    s[j]=t;
                    i++;
                    j--;
                }
                return s;//处理完这个特殊条件,必定结束了整个字符串的处理
            }
            else if(i+k-1>=s1)//特殊情况,<k
            {
                j=s1-1;
                while(i<j)
                {
                    t=s[i];
                    s[i]=s[j];
                    s[j]=t;
                    i++;
                    j--;
                }
                return s;
            }       
        }
        return s;//如果字符串为“abcd”,k=2,刚好只用到了正常情况
        
    }

上述代码实测9ms,beats 96.34% of cpp submissions。 

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档