G10: longest palindrome or every palindrome

Write a program that prints all the sub string that is palindrome within a input String. For e.g For input String "abbcacbca" output should be: [cac, bcacb, cbc, acbca, bb]

URL:  question?id=9689276


package careercup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class test1 {
	private Triplets trip = new Triplets(0, 0, 0);
	
	public static void main(String[] args) {
		String ss = "abba";
		new test1().isPalindrome(ss.toCharArray());
	}
	
	private void isPalindrome(char[] s){
		int len = s.length;
		int hit[][] = new int[len][len];
		
		for(int i=0; i<len;i++) {
			hit[i][i] = 1;
			//System.out.println(s[i]);
		}
		
		for(int i=0; i<len-1;i++) {
			if(s[i]==s[i+1]) {
				hit[i][i+1] = 2;
				System.out.println(s[i]+ ", " + s[i+1]);
			}
		}
		
		for(int k=2; k<len;k++) {
			for(int i=0; i<len-k; i++) {
				int j=i+k;
				if(s[i]==s[j] && hit[i+1][j-1]!=0) {
					hit[i][j]=k+1;
					if(k+1>trip.max) {
						trip.max = k+1;
						trip.low = i;
						trip.high = j;
					}
				} else {
					hit[i][j]=0;
				}
			}
		}
		
		System.out.print("max element is: ");
		print(s,trip.low, trip.high);
	}

	private static void print(char[] s, int i, int j) {
		String ss = new String(s,i,j-i+1);
		System.out.println(ss);
	}
	
	private class Triplets{
		public int max;
		public int low;
		public int high;
		public Triplets(int max, int low, int high){
			this.max = max;
			this.low = low;
			this.high = high;
		}
	}
}


posted @ 2013-02-08 15:57  西施豆腐渣  阅读(124)  评论(0编辑  收藏  举报