zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    找东西
    检测内存泄漏
    八月份月度反思
    博客之路
    快速开发~Rafy框架的初步认识
    VS快捷键的简单总结
    web前端使用工具的总结
    直接把数据库中的数据保存在CSV文件中
    AngularJs HTML DOM、AngularJS 事件以及模块的学习(5)
    AngularJS控制器和AngularJS过滤器的学习(3)
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6840756.html
Copyright © 2011-2022 走看看