📖

LeetCode #541 Reverse String Ⅱ

2024/10/11に公開

問題概要

入力値:s(string), k(int)
出力値:string
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
問題のリンク

入力例

Input: s="abcdefg", k=2
Output: "bacdfeg"

解答例1

計算量:O(n)
Two pointers
C++

class Solution {
public:
    string reverseStr(string s, int k) {
        int left = 0;
        int right = min(k, (int)s.size());

        while (left < s.size()) {
            reverse(s.begin() + left, s.begin() + right);
            left += 2 * k;
            right = min(left+k, (int)s.size());
        }
        return s;
    }
};

Runtime: 3ms
Beats: 85.08%

Discussion