Friday, September 13, 2013

WAP to find maximum possible pallendrome out of a given string

 static ArrayList<String> findMaxPalindrome(String str) {
        ArrayList<String> result = new ArrayList<String>();
        char[] ch = str.toCharArray();
        int ld = 0, rd = 0;
        for (int i = 0; i < ch.length - 1; i++) {
            if ((ch[i] == ch[i + 1]) || (i > 0 && ch[i - 1] == ch[i + 1])) {
                if (ch[i] == ch[i + 1]) {
                    ld = i - 1;
                    do{i++;}while(ch[i]==ch[i+1]);
                    rd = i + 1;
                } else if (i > 0) {
                    ld = i - 1;
                    rd = i + 1;
                }
                while (ld >= 0 && rd < ch.length) {
                    if (ch[ld] != ch[rd]) break;
                    ld--;   rd++;
                }
                if (rd - ld  > 3)
                    result.add(str.substring(ld+1, rd));
            }
        }
        return result;
    }

No comments:

Post a Comment