Split string to palindrome

Question:

Give a string, use minimum number of splits to divide the string into multiple parts in which each part a palindrome. For example, if the string is "abbad", we can split it into "abba" and "d", then the total splits is 1.

Idea:

In order to find the answer, we assume we have already found an answer for the first k characters, i.e., it needs m splits. Therefore, if there are k + 1 characters, the worst case is we need m + 1 splits. However, m + 1 may not be the best answer, why? if we can find a split point where the first portion is a palindrome, and the second portion is also a palindrome, the total splits may be less than m + 1. That is why we need to check the condition below.

if (isPalindrome(str, j, i) && cuts[i] > cuts[j - 1] + 1)
public class NumberOfSplits {
    public static void main(String[] args) {
        String str = "abbadd";
        System.out.println(new NumberOfSplits().numberOfSplits(str));
    }

    public int numberOfSplits(String str) {
        assert (str != null);
        int[] cuts = new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
            cuts[i] = i;
        }
        
        for (int i = 0; i < str.length(); i++) {
            if (isPalindrome(str, 0, i)) {
                cuts[i] = 0;
                continue;
            }
            for (int j = 1; j <= i; j++) {
                if (isPalindrome(str, j, i) && cuts[i] > cuts[j - 1] + 1) {
                    cuts[i] = cuts[j - 1] + 1;
                }
            }
        }
        return cuts[str.length() - 1];
    }
    
    public boolean isPalindrome(String str, int i, int j) {
        while (i <= j) {
            if (str.charAt(i) != str.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

 

posted @ 2015-01-26 05:46  北叶青藤  阅读(181)  评论(0)    收藏  举报