让我们知道您是否需要它(以及它是否具有良好的性能):
/** Transmitted max size between to parses */
static int maxSize = 0;
/**
* Said if the String is a palindrome.
*
* @param s
* sentence to parse.
*/
static void singlePalindrome(final String s) {
System.out.println("singlePalindrome: " + s);
final char[] word = s.toCharArray();
final int t = word.length;
boolean ok = true;
for (int i = t / 2; i > 0; i--) {
if (word[i - 1] != word[word.length - i]) {
ok = false;
break;
}
System.out.println((i - 1) + ":" + word[i - 1] + "\t" + (t - i)
+ ":" + word[t - i]);
}
System.out.println("It is " + (true == ok ? "" : "NOT ")
+ "a palindrome.");
}
/**
* Find all palindromes included anywhere in a sentence, with two search
* phases from left to right and right to left. Then keep the biggest one *
*
* @param sentence
* to parse
* @param len
* minimal size of palindrome(s) to find.
*/
static void palindromeNested(final String sentence, final int len) {
System.out.println(len + " = minimal size for palindromeNested(..): "
+ sentence);
int debS = 2;
String max = null;
while (debS <= sentence.length()) {
int i = debS / 2;
int cpt = 0;
for (; i <= debS; i++) {
++cpt;
if (sentence.charAt(i) == sentence.charAt(debS - i)) {
if (cpt >= len) {
final String sTmp = (i > debS - i) //
? sentence.substring(debS - i, i + 1) //
: sentence.substring(i, debS - i + 1);
final int maxTmp = sTmp.length();
if (maxTmp > maxSize) {
maxSize = maxTmp;
max = sTmp;
System.out.println(maxTmp + "\t" + max);
}
// System.out.format("%4d:%-4d %d :: %d %s,\n", i, debS
// - i, cpt, maxTmp, sTmp);
}
continue;
}
break;
}
debS++;
}
System.out.println("Result: " + max);
}
/** @param args */
public static void main(final String[] args) {
singlePalindrome("abccdccba");// "abccddccba" works
System.out.println("============================");
// "baabcc dd ccbaabiib" works like "baabcc d ccbaabiib" (odd problem)
final String words = "baabcc d ccbaabi o iba ab";
palindromeNested(new StringBuilder(words).reverse().toString(), 3); // 3carsMini
System.out.println("----------------------------");
palindromeNested(words, maxSize / 2); // the max found in first
System.out.println("============================");
}
}
输出 :
单回文:abccdccba
3:c 5:c
2:c 6:c
1:b 7:b
0:a 8:a
是回文。
============================
3 =回文嵌套的最小尺寸(..):ba abi o ibaabcc d ccbaab
5 ba ab
7 bi o ib
9 abi o iba
结果:abi o iba
----------------------------
4 = palindromeNested(..) 的最小尺寸: baabcc d ccbaabi o iba ab
11 abcc d ccba
13 aabcc d ccbaa
15 baabcc d ccbaab
结果:baabcc d ccbaab
========================== =