-
Notifications
You must be signed in to change notification settings - Fork 684
Expand file tree
/
Copy pathIsPalindrome.java
More file actions
61 lines (48 loc) · 1.86 KB
/
IsPalindrome.java
File metadata and controls
61 lines (48 loc) · 1.86 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
import java.util.Random;
public class IsPalindrome {
public static void main(String[] args) {
Random random = new Random();
String input = generateRandomString(random, 6);
boolean isPalindrome = isSpecial(input);
int longestPalindromeLength = getPalindromeLength(input);
System.out.println("Random String: " + input);
System.out.println("Is it a palindrome? " + isPalindrome);
System.out.println("Longest Palindromic Length: " + longestPalindromeLength);
}
public static boolean isSpecial(String text) {
String tempText = alterText(text);
return text.equals(tempText);
}
public static String alterText(String inputText) {
if (inputText == null || inputText.isEmpty()) {
return inputText;
}
return inputText.charAt(inputText.length() - 1) +
alterText(inputText.substring(0, inputText.length() - 1));
}
public static String generateRandomString(Random random, int length) {
String chars = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(chars.length());
sb.append(chars.charAt(randomIndex));
}
return sb.toString();
}
public static int getPalindromeLength(String text) {
String reversed = new StringBuilder(text).reverse().toString();
int maxLength = 0;
int currentLength = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reversed.charAt(i)) {
currentLength++;
if (currentLength > maxLength) {
maxLength = currentLength;
}
} else {
currentLength = 0;
}
}
return maxLength;
}
}