forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStringUsingStack.java
More file actions
34 lines (31 loc) · 1.01 KB
/
ReverseStringUsingStack.java
File metadata and controls
34 lines (31 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.thealgorithms.stacks;
import java.util.Stack;
public final class ReverseStringUsingStack {
private ReverseStringUsingStack() {
}
/**
* @param str string to be reversed using stack
* @return reversed string
*/
public static String reverse(String str) {
// Check if the input string is null
if (str == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
Stack<Character> stack = new Stack<>();
StringBuilder reversedString = new StringBuilder();
// Check if the input string is empty
if (str.isEmpty()) {
return str;
}
// Push each character of the string onto the stack
for (char ch : str.toCharArray()) {
stack.push(ch);
}
// Pop each character from the stack and append to the StringBuilder
while (!stack.isEmpty()) {
reversedString.append(stack.pop());
}
return reversedString.toString();
}
}