Reverse String II

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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.
LeetCode Problem - 541
class Solution {
public String reverseStr(String s, int k) {
// Create a StringBuilder to build the result string
StringBuilder sb = new StringBuilder();
// Case 1: If the string length is less than or equal to 'k', reverse the entire string
if(s.length() <= k){
sb.append(s);
return sb.reverse().toString();
}
// Case 2: If the string length is greater than 'k' but less than or equal to '2*k'
// Reverse the first 'k' characters, and keep the rest as is
else if (s.length() > k && s.length() <= 2 * k) {
sb.append(s.substring(0, k)); // Reverse the first 'k' characters
return (sb.reverse().toString()) + (s.substring(k, s.length())); // Concatenate the rest of the string
}
// Case 3: If the string length is greater than '2*k'
// Reverse the first 'k' characters of every 2*k chunk and keep the next 'k' characters as is
else if (s.length() > 2 * k) {
for(int i = 0; i < s.length(); i += 2 * k) {
// Reverse the first 'k' characters in the current 2*k chunk
String part1 = s.substring(i, Math.min(i + k, s.length()));
sb.append(new StringBuilder(part1).reverse());
// Append the next 'k' characters as is (if they exist)
if(i + k < s.length()) {
String part2 = s.substring(i + k, Math.min(i + 2 * k, s.length()));
sb.append(part2);
}
}
}
// Return the final constructed string
return sb.toString();
}
}




