1 * Difficulty: Primary
2 * Problem: Read the text from the input file calfflac.in, find the longest palindrome string (after flipping and its own equivalent string), only consider the letter, case-insensitive
3 * Outputs the length of the longest palindrome string and outputs its corresponding string in the original text. If multiple palindrome strings are equal in length, the output is the first.
4 * Note: The topic from: http://ace.delos.com/usacogate, interested friends can go to register, a good practice platform.
5*/
6import java.util.*;
7import java.io.*;
8class Calfflac
9{
Ten public static void Main (String [] args) throws IOException {
One//use BufferedReader rather than randomaccessfile; It ' s much faster
BufferedReader f = new BufferedReader (New FileReader ("calfflac.in"));
//input file name goes above
PrintWriter out = new PrintWriter (new BufferedWriter (New FileWriter ("Calfflac.out"));
String Temp=null;
StringBuilder origin=new StringBuilder (20000);//contains the original string
StringBuilder letters=new StringBuilder (20000);//contains letters
Int[] Indexes=new int[20000];
while ((Temp=f.readline ())!=null)
20 {
Origin.append (temp);
Origin.append (' \ n ');
23}
len=origin.length Int ();
for (int i=0;i<len;i++)
26 {
Char c= (Origin.charat (i));
if (c>= ' a ' &&c<= ' z ') | | c>= ' A ' &&c<= ' Z ')//As long as the letter
29 {
Letters.append (Origin.charat (i));
Indexes[letters.length () -1]=i;
32}
33}
int maxlength=1;//palindrome String length
The index of the middle letter of the int maxindex=0;//palindrome string
Len=letters.length ();
Panax for (int i=0;i<len;i++)//try each
38 {
The length=maxlength+1;//to find the next longer, because the topic requires, if it is of the same length, only outputs the front one.
The length of the Boolean ischanged=false;//palindrome string can be an odd number, or even several, which is used to toggle
A for (; I-(length-1)/2>=0&&i+length/2<len;)
42 {
43//Through the current I (middle of palindrome string), as well as length, find a section of string to be measured and test
if (Ispal letters,i-(length-1)/2,I+LENGTH/2))
45 {
Maxlength=length;
Maxindex=i;
length+=2;
49}
Or else if (!ischanged)//Toggle
51 {
Ischanged=true;
length++;//odd number and even number switch
54}
Or else
a break;
57}
58}
59//The following code, will find the palindrome string in the original string appearance.
int start=indexes[maxindex-(MAXLENGTH-1)/2];
end=indexes[maxindex+ Int (maxLength)/2];
The String result=origin.substring (start,end+1);
Out.println (maxLength);
OUT.PRINTLN (result);
Out.flush ();
Out.close ();
System.exit (0);
68}
69//Determine whether the string between I to J (included) in S is a palindrome.
Static Boolean Ispal (StringBuilder s,int i,int J)
71 {
A char c1= ' 0 ', c2= ' 0 ';
for (; i<j;i++,j--)
74 {
C1=s.charat (i);
C2=s.charat (j);
(c1!=c2&& (C1-C2)%32!=0)
The return false;
79}
is true;
81}
82}
83