Monday, February 1, 2016

Find the longest palindrome in a String

Find the longest palindrome in a String

public class LongestPalindrome {
            static int maxPalinLength;
            static String longestPal=null;
            public static void main(String[] args) {
                        System.out.println("Enter String");
                        Scanner scan = new Scanner(System.in);
                        String str = scan.next();
                        int length = str.length();
                        // Finding all combinations of String
                        for (int j = 0; j < length - 1; j++) {
                                    for (int i = j; i < length - 1; i++) {
                                                longestPalindrome(str.substring(j, i + 2));
                                    }
                        }
                        System.out.println("Longest Palindrome is "+ longestPal);
                        scan.close();
            }

            public static void longestPalindrome(String str) {
                        int length = str.length();
                        String reverse = "";
                        for (int i = length - 1; i >= 0; i--) {
                                    reverse = reverse + str.charAt(i);
                        }
                        // Checking if Strings are equal...
                        if (str.equals(reverse)) {
                                    // Finding the longest Palindrome
                                    if(length>maxPalinLength){
                                                longestPal=str;
                                                maxPalinLength=length;
                                    }
                        }
            }
}


Output:

Enter String
abfgerccdedccfgfer


Longest Palindrome is ccdedcc

No comments:

Post a Comment