[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

posted @ 2017-07-18 21:40  immjc  阅读(122)  评论(0编辑  收藏  举报