Skip to content

Commit 815c24f

Browse files
committed
refactor: remove main method and add JavaDoc to ReverseStringUsingStack
1 parent 6008fbf commit 815c24f

File tree

1 file changed

+17
-31
lines changed

1 file changed

+17
-31
lines changed
Lines changed: 17 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,38 @@
11
package com.thealgorithms.strings;
22

3-
import java.util.Scanner;
43
import java.util.Stack;
54

5+
/**
6+
* A utility class to reverse a given string using a Stack.
7+
*/
68
public final class ReverseStringUsingStack {
79

8-
/**
9-
* Main method to take user input and print the reversed string.
10-
*/
11-
public static void main(String[] args) {
12-
13-
// Create a Scanner object to read input from the user
14-
Scanner sc = new Scanner(System.in);
15-
System.out.print("Enter the String to reverse : ");
16-
String str = sc.nextLine();
17-
18-
// Call the reverse method and print the reversed string
19-
System.out.println("Reversed String : " + reverse(str));
20-
sc.close();
21-
}
22-
// Private constructor to hide implicit public one
10+
// Private constructor to prevent instantiation of utility class
2311
private ReverseStringUsingStack() {
2412
throw new UnsupportedOperationException("Utility class");
2513
}
2614

2715
/**
28-
* Reverses a string using a stack.
16+
* Reverses the input string using a Stack.
2917
*
30-
* @param str The input string to reverse
31-
* @return The reversed string
18+
* @param str the input string to be reversed
19+
* @return the reversed string
3220
*/
3321
public static String reverse(String str) {
34-
// StringBuilder to build the reversed string
3522
StringBuilder sb = new StringBuilder();
36-
// Stack to hold the characters of the string
37-
Stack<Character> st = new Stack<>();
23+
Stack<Character> stack = new Stack<>();
3824

39-
// Push each character of the string onto the stack
40-
for (int i = 0; i < str.length(); i++) {
41-
st.push(str.charAt(i));
25+
// Push each character of the string into the stack
26+
for (int i = 0; i < str.length(); ++i) {
27+
stack.push(str.charAt(i));
4228
}
4329

44-
// Pop characters from the stack and append to StringBuilder
45-
while (!st.empty()) {
46-
sb.append(st.pop());
30+
// Pop each character from the stack and append to StringBuilder
31+
while (!stack.isEmpty()) {
32+
sb.append(stack.pop());
4733
}
48-
// Convert StringBuilder to String and return
49-
String rev = sb.toString();
50-
return rev;
34+
35+
// Return the reversed string
36+
return sb.toString();
5137
}
5238
}

0 commit comments

Comments
 (0)