mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Add ReverseStringUsingStack (#6452)
* Refactored ReverseStringUsingStack * Add ReverseStringUsingStack * Refactored ReverseStringUsingStack * Closes #6451
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user