Skip to content

Commit 03c234b

Browse files
committed
Refactored ReverseStringUsingStack utility for reversing strings using stack
1 parent 24f4090 commit 03c234b

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.stacks;
2+
3+
import java.util.Stack;
4+
5+
public final class ReverseStringUsingStack {
6+
private ReverseStringUsingStack() {
7+
}
8+
9+
/**
10+
* @param str string to be reversed using stack
11+
* @return reversed string
12+
*/
13+
public static String reverse(String str) {
14+
// Check if the input string is null
15+
if (str == null) {
16+
throw new IllegalArgumentException("Input string cannot be null");
17+
}
18+
Stack<Character> stack = new Stack<>();
19+
StringBuilder reversedString = new StringBuilder();
20+
// Check if the input string is empty
21+
if (str.isEmpty()) {
22+
return str;
23+
}
24+
// Push each character of the string onto the stack
25+
for (char ch : str.toCharArray()) {
26+
stack.push(ch);
27+
}
28+
// Pop each character from the stack and append to the StringBuilder
29+
while (!stack.isEmpty()) {
30+
reversedString.append(stack.pop());
31+
}
32+
return reversedString.toString();
33+
}
34+
}

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+
/**
64+
* Reverse version 4 the given string using a Stack.
65+
* This method pushes each character of the string onto a stack
66+
* and then pops them off to create the reversed string.
67+
*/
68+
public static String reverse4(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
}

0 commit comments

Comments
 (0)