Skip to content

Commit 0f97806

Browse files
committed
Add ReverseStringUsingStack utility for reversing strings using stack
1 parent 24f4090 commit 0f97806

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
Stack<Character> stack = new Stack<>();
15+
StringBuilder reversedString = new StringBuilder();
16+
// Check if the input string is empty
17+
if (str.isEmpty()) {
18+
return str;
19+
}
20+
// Push each character of the string onto the stack
21+
for (char i : str.toCharArray()) {
22+
stack.push(i);
23+
}
24+
// Pop each character from the stack and append to the StringBuilder
25+
while (!stack.isEmpty()) {
26+
reversedString.append(stack.pop());
27+
}
28+
return reversedString.toString();
29+
}
30+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy