File tree Expand file tree Collapse file tree 1 file changed +25
-1
lines changed
src/main/java/com/thealgorithms/strings Expand file tree Collapse file tree 1 file changed +25
-1
lines changed Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .strings ;
2
2
3
+ import java .util .Stack ;
4
+
3
5
/**
4
6
* Reverse String using different version
5
7
*/
@@ -57,4 +59,26 @@ public static String reverse3(String string) {
57
59
}
58
60
return sb .toString ();
59
61
}
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