zoukankan      html  css  js  c++  java
  • [LeetCode] 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:

    1. The string consists of lower English letters only.
    2. Length of the given string and k will in the range [1, 10000]

    对字符串进行反转,规则是:每隔k个反转k个字母。如果剩下的字母不满足k则,则将剩下的字母全部反转。取t = n / k,将字符串分成k份,每隔一份反转一次。

    class Solution {
    public:
        string reverseStr(string s, int k) {
            int n = s.size(), t = n / k;
            for (int i = 0; i <= t; i++) {
                if (i % 2 == 0) {
                    if (i * k + k < n)
                        reverse(s.begin() + i * k, s.begin() + i * k + k);
                    else
                        reverse(s.begin() + i * k, s.end());
                }
            }
            return s;
        }
    };
    // 6 ms

     相关题目:Reverse String

  • 相关阅读:
    View Controller 生命周期的各个方法的用法
    IOS开发之Post 方式获取服务器数据
    委托代理
    Function
    SKPhysicsContactDelegate协议
    UITouch附加
    Remove Duplicates from Sorted Array II
    4Sum
    [Text Justification
    Count and Say
  • 原文地址:https://www.cnblogs.com/immjc/p/7202861.html
Copyright © 2011-2022 走看看