Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.thealgorithms.strings;

import java.util.Stack;

/**
* A utility class to reverse a given string using a Stack.
*/
public final class ReverseStringUsingStack {

// Private constructor to prevent instantiation of utility class
private ReverseStringUsingStack() {
throw new UnsupportedOperationException("Utility class");
}

/**
* Reverses the input string using a Stack.
*
* @param str the input string to be reversed
* @return the reversed string
*/
public static String reverse(String str) {
StringBuilder sb = new StringBuilder();
Stack<Character> stack = new Stack<>();

// Push each character of the string into the stack
for (int i = 0; i < str.length(); ++i) {
stack.push(str.charAt(i));
}

// Pop each character from the stack and append to StringBuilder
while (!stack.isEmpty()) {
sb.append(stack.pop());
}

// Return the reversed string
return sb.toString();
}
}