Split string to palindrome

来源:互联网 发布:淘宝吊带碎花连衣裙 编辑:程序博客网 时间:2024/04/29 16:14

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.

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;}}


 

原创粉丝点击