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]

    思路:

    以2*k 为一组,每一组前k个字符翻转,然后处理剩余字符。

    写出来感觉好啰嗦。。另外简洁的代码看到大神有用stl的reverse的,回头试一下,省不少事儿。

    string reverseStr(string s, int k)
         {
             int group = s.size()/(2*k);
             int i = 0;
             for (; i < group;i++)
             {
                 for (int j = 0; j < k/2;j++)
                 {
                     swap(s[i * 2 * k + j], s[i * 2 * k + k-j-1]);
                 }
             }
             int remain = s.size() % (2 * k);
             int end = (remain >= k) ? k : remain ;
             for (int j = 0; j < end/2;j++)
             {
                 swap(s[i * 2 * k + j], s[i * 2 * k + end - j - 1]);
             }
             return s;
         }
  • 相关阅读:
    c#对XML读取
    WPF--TypeConverter使用
    WPF---对于没有Command属性的添加以下代码可以达到有Command效果
    自定义事件、属性、方法
    读取Excel文件
    ClickOnce安装部署,手动。
    Logger 日志记录
    Maven
    等待与通知范式
    线程状态及基本方法
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6838426.html
Copyright © 2011-2022 走看看