Skip to content

Commit a1a05a1

Browse files
committed
Refactored ReverseStringUsingStack utility for reversing strings using stack
1 parent efc2580 commit a1a05a1

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

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

Lines changed: 25 additions & 1 deletion
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,26 @@ public static String reverse3(String string) {
5759
}
5860
return sb.toString();
5961
}
60-
}
62+
/**
63+
* Reverse version 4 the given string using a Stack.
64+
* This method pushes each character of the string onto a stack
65+
* and then pops them off to create the reversed string.
66+
*/
67+
public static String reverse4(String str) {
68+
Stack<Character> stack = new Stack<>();
69+
StringBuilder reversedString = new StringBuilder();
70+
// Check if the input string is empty
71+
if (str.isEmpty()) {
72+
return str;
73+
}
74+
// Push each character of the string onto the stack
75+
for (char i : str.toCharArray()) {
76+
stack.push(i);
77+
}
78+
// Pop each character from the stack and append to the StringBuilder
79+
while (!stack.isEmpty()) {
80+
reversedString.append(stack.pop());
81+
}
82+
return reversedString.toString();
83+
}
84+
}

0 commit comments

Comments
 (0)