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