跳转至

541.Reverse String II

Tags: String Two Pointers Easy

Links: https://leetcode.com/problems/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]

class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.size();
        int cur = 0, next = 2 * k - 1;

        while (next < n) {
            reverse(s.begin() + cur, s.begin() + cur + k);
            cur = next + 1;
            next = cur + 2 * k - 1;
        }
        int len = n - cur;
        if (k <= len && len < 2 * k) {
            reverse(s.begin() + cur, s.begin() + cur + k);
        }
        else if (len < k) {
            reverse(s.begin() + cur, s.end());
        }

        return s;
    }
};

直接模拟即可,相比于链表,可以利用下标进行随机访问,就不用逐个探测了。