Find all possible palindromes in a String in java

 Find all possible palindromes in a String in java

To find all palindromic substrings in a given string in Java, you can use the following approach:



  1. Iterate over the characters in the string and for each character, consider all substrings that start and end with that character.
  2. For each of these substrings, check if it is a palindrome by comparing the first and last characters, then the second and second-to-last characters, and so on, until you reach the middle of the string. If all the pairs of characters match, then the substring is a palindrome.
  3. Add the palindromic substrings to a list or set, and return the list or set when you have finished iterating over the characters in the string.

Here is an example of how you might implement this in Java:



import java.util.ArrayList;

import java.util.List;


class PalindromeFinder {

  public static List<String> findAllPalindromes(String s) {

    List<String> palindromes = new ArrayList<>();

    for (int i = 0; i < s.length(); i++) {

      for (int j = i + 1; j <= s.length(); j++) {

        String substring = s.substring(i, j);

        if (isPalindrome(substring)) {

          palindromes.add(substring);

        }

      }

    }

    return palindromes;

  }


  private static boolean isPalindrome(String s) {

    for (int i = 0; i < s.length() / 2; i++) {

      if (s.charAt(i) != s.charAt(s.length() - i - 1)) {

        return false;

      }

    }

    return true;

  }

}


String s = "BCdedCB";
List<String> palindromes = PalindromeFinder.findAllPalindromes(s);
System.out.println(palindromes); // Outputs ["BCdedCB", "CdedC","ded"]

Post a Comment

0 Comments