Skip to content

Commit 5bc3d75

Browse files
authored
Merge pull request #8 from kylewehrung/java-practice
added a palindrome length checker
2 parents 9357e31 + ac8b82d commit 5bc3d75

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

ch04/IsPalindrome.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ public static void main(String[] args) {
55
Random random = new Random();
66
String input = generateRandomString(random, 6);
77
boolean isPalindrome = isSpecial(input);
8+
int longestPalindromeLength = getPalindromeLength(input);
89
System.out.println("Random String: " + input);
910
System.out.println("Is it a palindrome? " + isPalindrome);
11+
System.out.println("Longest Palindromic Length: " + longestPalindromeLength);
1012
}
1113

1214
public static boolean isSpecial(String text) {
@@ -31,5 +33,29 @@ public static String generateRandomString(Random random, int length) {
3133
}
3234
return sb.toString();
3335
}
36+
37+
public static int getPalindromeLength(String text) {
38+
String reversed = new StringBuilder(text).reverse().toString();
39+
int maxLength = 0;
40+
int currentLength = 0;
41+
42+
for (int i = 0; i < text.length(); i++) {
43+
if (text.charAt(i) == reversed.charAt(i)) {
44+
currentLength++;
45+
if (currentLength > maxLength) {
46+
maxLength = currentLength;
47+
}
48+
} else {
49+
currentLength = 0;
50+
}
51+
}
52+
return maxLength;
53+
}
54+
55+
56+
3457
}
3558

59+
60+
61+

0 commit comments

Comments
 (0)