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;
    }
};
posted @ 2018-12-05 22:32  A-Little-Nut  阅读(121)  评论(0编辑  收藏  举报