Search code examples
javaloopspalindrome

find all palindromes in string


I need to find all the palindromes in a string. It takes user input

example: "abbaalla"

it loops through creating a substring that changes as the loop progresses.

example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..

once it reaches the max length of the word it iterates the start of the substring and repeats

example: check palindrome "b" "bb" "bba" and so on..

I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"

the final output should be a string that includes all palindromes. in this case;

output: "abba alla"

Also this program currently results in: String index out of range: -1

 public static String findAllPalindromes(String input){
     int indexStart = 0;
     int wordMax = input.length();
     int wordLength;
     String checkPalindrome;
     String allPalindromes = "";
     for (wordLength = 2; wordLength <= wordMax; wordLength++) {

         //creates a substring to check against isAllPalindrome method
         checkPalindrome = input.substring(indexStart, wordLength);
         //checks checkPalindrome string to see if it is a palindrome
         if (isAllPalindrome(checkPalindrome) == true){
             allPalindromes += " " + checkPalindrome;
             if (checkPalindrome.length() >= allPalindromes.length()){
                 allPalindromes = checkPalindrome;
             }
         }
         //once program reads string through once, increment index and scan text again
         if (wordLength == wordMax && indexStart < wordMax){
             indexStart++;
             wordLength = 0;
         }

     }
     System.out.println("The palindromes in the text are: ");
     System.out.println(allPalindromes);
     return allPalindromes;
 }

Solution

  • public static Set<CharSequence> printAllPalindromes(String input) {
        if (input.length() <= 2) {
            return Collections.emptySet();
        }
        Set<CharSequence> out = new HashSet<CharSequence>();
        int length = input.length();
        for (int i = 1; i <= length; i++) {
            for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
                if (input.charAt(j) == input.charAt(k)) {
                    out.add(input.subSequence(j, k + 1));
                } else {
                    break;
                }
            }
        }
        return out;
    }