Leetcode 541. Reverse String II
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer 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 leave the other as original.
s
will only contain lowercase English letters.s
and the integer k
?
s
has a length of up to 10000 characters, and k
is in the range from 1 to 10000.2k
characters.k
Characters of Each Chunk:
2k
characters, I will reverse the first k
characters. If a chunk has less than 2k
characters left, the chunk will be accordingly smaller.k
, I will reverse all of them.k
but fewer than 2k
, I will reverse the first k
characters while keeping the rest unchanged.#include <string>
#include <algorithm> // For std::reverse
std::string reverseStr(std::string s, int k) {
int n = s.size();
for (int start = 0; start < n; start += 2 * k) {
// Determine the end of the current segment to process
int end = std::min(start + k, n);
// Reverse the first k characters in the current segment
std::reverse(s.begin() + start, s.begin() + end);
}
return s;
}
s
. We are traversing the entire string one time and performing reversals on segments which are in total linear time operations.This implementation efficiently processes the string with the given constraints and correctly applies the required transformations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?