Skip to content

Commit e09c985

Browse files
authored
Add ReverseStringUsingStack (#6452)
* Refactored ReverseStringUsingStack * Add ReverseStringUsingStack * Refactored ReverseStringUsingStack * Closes #6451
1 parent 24f4090 commit e09c985

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.thealgorithms.strings;
22

3+
import java.util.Stack;
4+
35
/**
46
* Reverse String using different version
57
*/
@@ -57,4 +59,31 @@ public static String reverse3(String string) {
5759
}
5860
return sb.toString();
5961
}
62+
/**
63+
* Reverses the given string using a stack.
64+
* This method uses a stack to reverse the characters of the string.
65+
* * @param str The input string to be reversed.
66+
* @return The reversed string.
67+
*/
68+
public static String reverseStringUsingStack(String str) {
69+
// Check if the input string is null
70+
if (str == null) {
71+
throw new IllegalArgumentException("Input string cannot be null");
72+
}
73+
Stack<Character> stack = new Stack<>();
74+
StringBuilder reversedString = new StringBuilder();
75+
// Check if the input string is empty
76+
if (str.isEmpty()) {
77+
return str;
78+
}
79+
// Push each character of the string onto the stack
80+
for (char ch : str.toCharArray()) {
81+
stack.push(ch);
82+
}
83+
// Pop each character from the stack and append to the StringBuilder
84+
while (!stack.isEmpty()) {
85+
reversedString.append(stack.pop());
86+
}
87+
return reversedString.toString();
88+
}
6089
}

src/test/java/com/thealgorithms/strings/ReverseStringTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.thealgorithms.strings;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import java.util.stream.Stream;
7+
import org.junit.jupiter.api.Test;
68
import org.junit.jupiter.params.ParameterizedTest;
79
import org.junit.jupiter.params.provider.Arguments;
810
import org.junit.jupiter.params.provider.MethodSource;
@@ -31,4 +33,15 @@ public void testReverseString2(String input, String expectedOutput) {
3133
public void testReverseString3(String input, String expectedOutput) {
3234
assertEquals(expectedOutput, ReverseString.reverse3(input));
3335
}
36+
37+
@ParameterizedTest
38+
@MethodSource("testCases")
39+
public void testReverseStringUsingStack(String input, String expectedOutput) {
40+
assertEquals(expectedOutput, ReverseString.reverseStringUsingStack(input));
41+
}
42+
43+
@Test
44+
public void testReverseStringUsingStackWithNullInput() {
45+
assertThrows(IllegalArgumentException.class, () -> ReverseString.reverseStringUsingStack(null));
46+
}
3447
}

0 commit comments

Comments
 (0)