File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/strings Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package 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+ }
You can’t perform that action at this time.
0 commit comments