Asked 9 months ago
0Comments
0 Views
The problem "Reverse String II" asks us to perform a specific string manipulation:
s
and an integer k
.k
characters of every 2k
chunk of the string.k
characters left at the end, we reverse all of them.k
and 2k
characters left, we reverse only the first k
.What We Need to Find: We need to return the modified string after applying these reversal rules.
Approach and Intuition:
2k
characters.k
characters.Let's break down the code into more understandable blocks:
class Solution {
public:
string reverseStr(string s, int k) {
int stringLength = s.length();
for (int start = 0; start < stringLength; start += 2*k) {
// Determine the end point for reversal
int end = min(start + k, stringLength);
// Reverse the substring from start to end
reverse(s.begin() + start, s.begin() + end);
}
return s;
}
};
The beauty of this solution is that it automatically handles all the edge cases mentioned in the problem statement:
k
characters left, it will reverse all of them.k
and 2k
characters left, it will only reverse the first k
.This approach is efficient because it modifies the string in-place, avoiding unnecessary memory allocation
Using While LOOP !
class Solution {
public:
string reverseStr(string s, int k) {
int left = 0; // starting index of the window
int right = min(k, (int)s.length()); // ending index of the window
while (left < s.length()) {
// Reverse the substring between left and right
reverse(s.begin() + left, s.begin() + right);
// Move the window 2k steps forward
left += 2 * k;
right = min(left + k, (int)s.length());
}
return s;
}
};
public class Solution {
public String reverseStr(String s, int k) {
int left = 0;
int right = Math.min(k, s.length());
StringBuilder sb = new StringBuilder(s);
while (left < s.length()) {
StringBuilder temp = new StringBuilder(sb.substring(left, right));
sb.replace(left, right, temp.reverse().toString());
left += 2 * k;
right = Math.min(left + k, s.length());
}
return sb.toString();
}
}
Share