zoukankan      html  css  js  c++  java
  • 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 = 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。 

  • 相关阅读:
    最近碰到的一些问题
    CF #365 703D. Mishka and Interesting sum
    CF 690C3. Brain Network (hard) from Helvetic Coding Contest 2016 online mirror (teams, unrated)
    Mac Hadoop的安装与配置
    pyenv的安装和使用
    tmux简要介绍
    将本地的项目通过SVN还原到某一版本,并将SVN服务器上的项目也还原到这一版本
    Tomcat7解决中文乱码
    解决tomcat7控制台中文乱码问题
    JDK环境变量配置,实现多个版本的JDK环境变量任意切换配置(Windows7 / Windows10 )
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8976322.html
Copyright © 2011-2022 走看看