Add ReverseStringUsingStack (#6452)

* Refactored ReverseStringUsingStack
* Add ReverseStringUsingStack
* Refactored ReverseStringUsingStack
* Closes #6451
This commit is contained in:
Navaneedan S
2025-08-02 00:46:10 +05:30
committed by GitHub
parent 24f4090210
commit e09c98578f
2 changed files with 42 additions and 0 deletions

View File

@@ -1,5 +1,7 @@
package com.thealgorithms.strings;
import java.util.Stack;
/**
* Reverse String using different version
*/
@@ -57,4 +59,31 @@ public final class ReverseString {
}
return sb.toString();
}
/**
* Reverses the given string using a stack.
* This method uses a stack to reverse the characters of the string.
* * @param str The input string to be reversed.
* @return The reversed string.
*/
public static String reverseStringUsingStack(String str) {
// Check if the input string is null
if (str == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
Stack<Character> stack = new Stack<>();
StringBuilder reversedString = new StringBuilder();
// Check if the input string is empty
if (str.isEmpty()) {
return str;
}
// Push each character of the string onto the stack
for (char ch : str.toCharArray()) {
stack.push(ch);
}
// Pop each character from the stack and append to the StringBuilder
while (!stack.isEmpty()) {
reversedString.append(stack.pop());
}
return reversedString.toString();
}
}

View File

@@ -1,8 +1,10 @@
package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@@ -31,4 +33,15 @@ public class ReverseStringTest {
public void testReverseString3(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverse3(input));
}
@ParameterizedTest
@MethodSource("testCases")
public void testReverseStringUsingStack(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverseStringUsingStack(input));
}
@Test
public void testReverseStringUsingStackWithNullInput() {
assertThrows(IllegalArgumentException.class, () -> ReverseString.reverseStringUsingStack(null));
}
}