2023-05-07 15:19:23 +03:00
|
|
|
package OOP.Java.lab_3;
|
|
|
|
|
|
|
|
public class lab_3 {
|
|
|
|
static int maxStrLength;
|
|
|
|
static String result;
|
|
|
|
|
2023-05-07 17:07:56 +03:00
|
|
|
public static void cSubUtil(StringBuilder stringbuilder, int leftBoundary, int rightBoundary) {
|
|
|
|
String string = stringbuilder.toString().toLowerCase().replaceAll("[^a-z]","");
|
2023-05-07 15:19:23 +03:00
|
|
|
// check if the indices lie in the range of string
|
|
|
|
// and also if it is palindrome
|
|
|
|
while (leftBoundary >= 0 && rightBoundary < string.length() && string.toLowerCase().charAt(leftBoundary) == string.toLowerCase().charAt(rightBoundary)) {
|
|
|
|
// expand the boundary
|
|
|
|
leftBoundary--;
|
|
|
|
rightBoundary++;
|
|
|
|
}
|
2023-06-05 16:37:15 +03:00
|
|
|
// if it's length is greater than maxStrLength update
|
|
|
|
// maxLength and result
|
2023-05-07 15:19:23 +03:00
|
|
|
if (rightBoundary - leftBoundary - 1 >= maxStrLength) {
|
|
|
|
result = string.substring(leftBoundary + 1, rightBoundary);
|
|
|
|
maxStrLength = rightBoundary - leftBoundary - 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-07 17:07:56 +03:00
|
|
|
public static int longestPalSubstr(StringBuilder string)
|
2023-05-07 15:19:23 +03:00
|
|
|
{
|
|
|
|
result = "";
|
|
|
|
maxStrLength = 1;
|
|
|
|
// for every index in the string check palindromes
|
|
|
|
// starting from that index
|
|
|
|
for (int i = 0; i < string.length(); i++) {
|
|
|
|
// check for odd length palindromes
|
|
|
|
cSubUtil(string, i, i);
|
|
|
|
// check for even length palindromes
|
|
|
|
cSubUtil(string, i, i + 1);
|
|
|
|
}
|
2023-05-07 17:07:56 +03:00
|
|
|
System.out.println("Longest palindrome substring is: " + compareStrings(string));
|
|
|
|
return compareStrings(string).length();
|
2023-05-07 15:19:23 +03:00
|
|
|
}
|
|
|
|
|
2023-05-07 16:46:18 +03:00
|
|
|
public static String compareStrings(StringBuilder builder) {
|
2023-05-07 17:07:56 +03:00
|
|
|
for (int leftBoundary = 0; leftBoundary <= builder.length(); leftBoundary++) {
|
2023-05-08 10:53:20 +03:00
|
|
|
for (int rightBoundary = builder.length(); rightBoundary >= leftBoundary; rightBoundary--) {
|
2023-05-08 10:51:54 +03:00
|
|
|
if (result.equals(builder.substring(leftBoundary, rightBoundary).toLowerCase().replaceAll("[^a-z]",""))) {
|
|
|
|
return builder.substring(leftBoundary, rightBoundary);
|
2023-05-07 16:46:18 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
2023-05-07 15:19:23 +03:00
|
|
|
public static void main(String[] args) {
|
|
|
|
StringBuilder stringToDetect = new StringBuilder("Eva, can I see bees in a cave?");
|
|
|
|
|
2023-05-08 10:53:20 +03:00
|
|
|
System.out.println("Initial string: " + stringToDetect);
|
2023-05-07 17:07:56 +03:00
|
|
|
System.out.println("Length is: " + longestPalSubstr(stringToDetect));
|
2023-05-07 15:19:23 +03:00
|
|
|
}
|
|
|
|
}
|