Pages

Tuesday 18 September 2012

UVA - 353 - Pesky Palindromes


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer("");
        String m;
        ArrayList<String> found=new ArrayList<String>();
        while((m=br.readLine())!=null){
            m=m.trim();
            found.clear();
            StringBuilder temp=new StringBuilder("");
            for(int i=0;i<m.length();i++){
                temp=new StringBuilder(m.charAt(i)+"");
                if(pali(temp.toString())){
                        if(!found.contains(temp.toString())){
                            found.add(temp.toString());
                        }
                    }
                for(int j=i+1;j<m.length();j++){
                    temp.append(m.charAt(j));
                    if(pali(temp.toString())){
                        if(!found.contains(temp.toString())){
                            found.add(temp.toString());
                        }
                    }
                }
            }
            sb.append("The string \'") .append(m).append("\' contains ").append(found.size()).append(" palindromes.\n");    
        }
        System.out.print(sb);
    }
   
    static boolean pali(String s) {
        for (int i = 0, j = s.length() - 1; i < s.length() / 2; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}

No comments:

Post a Comment