Skip to content

Commit d0bfef2

Browse files
committed
Updated ReverseString class to use recursion
1 parent 4d28c88 commit d0bfef2

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/main/java/com/thealgorithms/strings/ReverseString.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,19 @@ public static String reverseStringUsingStack(String str) {
8686
}
8787
return reversedString.toString();
8888
}
89+
90+
/**
91+
* Reverse a string using recursion
92+
*
93+
* @param str The input string to reverse
94+
* @return Reversed string
95+
*/
96+
public static String reverseRecursive(String str) {
97+
// Base case: if string is empty or single character
98+
if (str == null || str.length() <= 1) {
99+
return str;
100+
}
101+
// Recursive step: last char + reverse of rest of string
102+
return str.charAt(str.length() - 1) + reverseRecursive(str.substring(0, str.length() - 1));
103+
}
89104
}

0 commit comments

Comments
 (0)