541. Reverse String II(LeetCode)

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]
     1 class Solution {
     2 public:
     3     string reverseStr(string s, int k) {
     4             int len = s.size();
     5         string s1 = "";
     6         if (len<k)
     7         {
     8             for (int i = len - 1; i >= 0; i--)
     9             {
    10                 s1 += s[i];
    11             }
    12         }
    13         else
    14         {
    15             for (int i = 0; i < len; i = i + 2*k)
    16             {
    17               for(int j=(i+k-1>len?len-1:(i+k-1));j>=i;j--)
    18               {
    19                   s1+=s[j];
    20               }
    21               for(int j=i+k;j<((i+2*k)>len?len:(i+2*k));j++)
    22               {
    23                   s1+=s[j];
    24               }
    25             }
    26         }
    27         return s1;
    28     }
    29 };

    我的代码普遍有个特点,就是暴力,哎,什么时候才能学会取巧呢?下面的是比较好的算法。

     1 class Solution {
     2     void reverse(string &s, int l, int r)
     3     {
     4         if (r > (s.length() - 1))
     5             r = s.length() - 1;
     6         while (l < r)
     7         {
     8             swap(s[l], s[r]);
     9             l++;
    10             r--;
    11         }
    12     }
    13 public:
    14     string reverseStr(string s, int k) {
    15 
    16         for (int i = 0; i<s.length(); i += 2 * k)
    17         {
    18             reverse(s, i, i + k - 1);
    19         }
    20 
    21         return s;
    22     }
    23 };
原文地址:https://www.cnblogs.com/wujufengyun/p/6840756.html