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:

    • The string consists of lower English letters only.
    • Length of the given string and k will in the range [1, 10000]
    class Solution { //自己练习用递归实现string 的 reverse
    public:
        string help(string s){
            if(s=="")
                return s;
            else
                return help(s.substr(1,s.size())) + s[0];
        }
        string reverseStr(string s, int k) {
            string ans = "";
            int i=0, size = s.size();
            for(; i<=size-2*k; i+=2*k){
                ans += help(s.substr(i,k));
                ans += s.substr(i+k, k);
            }
            if(s.size()-i < k)
                 ans += help(s.substr(i, s.size()-i));
            else{
                 ans += help(s.substr(i, k));
                 ans += s.substr(i+k, s.size()-k);
            }
            return ans;
        }
    };
    
  • 相关阅读:
    再逛开心网
    WAPM
    win2003安装flash cs4
    [AS3][物体的运动]
    转sql产生百万记录
    KeyedList
    timer 焦点
    sql优化
    灰色
    参数
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10073928.html
Copyright © 2011-2022 走看看