|
1 | 1 | package com.thealgorithms.strings;
|
2 | 2 |
|
3 |
| -import java.util.Scanner; |
4 | 3 | import java.util.Stack;
|
5 | 4 |
|
| 5 | +/** |
| 6 | + * A utility class to reverse a given string using a Stack. |
| 7 | + */ |
6 | 8 | public final class ReverseStringUsingStack {
|
7 | 9 |
|
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 |
23 | 11 | private ReverseStringUsingStack() {
|
24 | 12 | throw new UnsupportedOperationException("Utility class");
|
25 | 13 | }
|
26 | 14 |
|
27 | 15 | /**
|
28 |
| - * Reverses a string using a stack. |
| 16 | + * Reverses the input string using a Stack. |
29 | 17 | *
|
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 |
32 | 20 | */
|
33 | 21 | public static String reverse(String str) {
|
34 |
| - // StringBuilder to build the reversed string |
35 | 22 | 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<>(); |
38 | 24 |
|
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)); |
42 | 28 | }
|
43 | 29 |
|
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()); |
47 | 33 | }
|
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(); |
51 | 37 | }
|
52 | 38 | }
|
0 commit comments