Groovy String Reversal
class StringReverser { String reverseString(String input) { if (input == null || input.length() <= 1) { return input; } return reverseHelper(input, input.length() - 1); } private String reverseHelper(String str, int index) { if (index < 0) { return ""; } return str.charAt(index)...
This Groovy code defines a class `StringReverser` with a method to reverse a given string. It uses a recursive helper function to build the reversed string character by character. This is a fundamental string manipulatio...
The `reverseString` method handles null or short strings as base cases. The `reverseHelper` function recursively appends the character at the current index to the result of reversing the rest of the string. The time complexity is O(n) because each character is processed once. The space complexity is also O(n) due to the recursive call stack. Edge cases like empty strings and single-character strings are explicitly handled, ensuring correctness.
function reverseString(input): if input is null or length of input is 0 or 1: return input return reverseHelper(input, length of input - 1) function reverseHelper(str, index): if index is less than 0: return empty string...