[英]generate longest possible palindrome for a given string
我一直在嘗試用 java 生成包含在給定字符串中的最長可能回文。 但是,它總是以錯誤告終。
讓我提供示例輸入和輸出,以便它可能有所幫助。
輸入: This is a sample string for testing
輸出: ttissaepeassitt
如果有人能解決我這個問題就太好了!!
謝謝你!!
您可以使用遞歸算法:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.