• [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

  • 相关阅读:
    匿名对象
    封装性
    1 Django初探
    8 定制10MINs 3
    7 定制10MINs首页2
    5-1 练习css 总结
    6.定制10MINS首页1
    3-1 练习 HTML 总结
    5. css定位 居中
    4 CSS的20/80个知识点
  • 原文地址:https://www.cnblogs.com/immjc/p/7202861.html
Copyright © 2020-2023  润新知