简体   繁体   中英

generate longest possible palindrome for a given string

I've been trying to generate the longest possible palindrome included in a given string, in java. But, it always ended up in errors.

Let me provide the sample input and output so that it may help .

Input: This is a sample string for testing

Output: ttissaepeassitt

It would be great if anyone could solve me this!!

Thank You!!

You could use a recursive algorithm:

public String findPalindrom(String input){
   String palindrom = "";
   for(int i=0; i<input.length(); i++){
      char c = input.charAt(i); // Explore the string from the beginning, char by char
      for(int j=input.length()-1; j>i; j--){ // Explore the string from the end, char by char
         if(input.charAt(j)==c){ // We found a letter for the palindrom
            String newPalindrom = c + findPalindrom(input.substring(i+1, j)) + c;
            if(newPalindrom.length() > palindrom.length())
               palindrom = newPalindrom;
         }
      }
   }
   if(palindrom.length()==0 && input.length()>0)
      palindrom += input.charAt(0); // manage the case where the only palindrom possible is a single char.
   return palindrom;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM