-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseString.java
More file actions
69 lines (51 loc) · 1.92 KB
/
Copy pathReverseString.java
File metadata and controls
69 lines (51 loc) · 1.92 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package algorithms.classics;
import java.util.logging.*;
/*
https://www.geeksforgeeks.org/java/reverse-a-string-in-java/
* Reverse a String without using built-in methods like StringBuilder.reverse()
*/
public class ReverseString {
private static final Logger LOGGER = Logger.getLogger(ReverseString.class.getName());
// Private constructor to prevent instantiation
private ReverseString() {
throw new IllegalStateException("Utility class");
}
// Manual approach: Two pointers swapping characters in a char array
public static String reverseManual(String text) {
if (text == null) {
return null;
}
char[] chars = text.toCharArray();
int left = 0;
int right = chars.length - 1;
// Swap characters until the pointers meet in the middle
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
// Recursive approach
public static String reverseRecursive(String text) {
if (text == null) {
return null;
}
if (text.isEmpty()) {
return text;
}
return reverseRecursive(text.substring(1)) + text.charAt(0);
}
public static void main() {
String original = "Java Fundamentals";
// Logging the original and reversed strings using both methods
LOGGER.info(() -> "Original: " + original);
LOGGER.info(() -> "Reversed (manual): " + reverseManual(original));
LOGGER.info(() -> "Reversed (recursive): " + reverseRecursive(original));
// Demonstrating the built-in method for comparison
String withStringBuilder = new StringBuilder(original).reverse().toString();
LOGGER.info(() -> "Reversed (built-in): " + withStringBuilder);
}
}