Palindrome Partitioning II

来源:互联网 发布:淘宝让上传身份证清关 编辑:程序博客网 时间:2024/04/23 16:02

1.题目

给定一个字符串s,将s分割成一些子串,使每个子串都是回文。

返回s符合要求的的最少分割次数。

比如,给出字符串s = "aab"

返回 1, 因为进行一次分割可以将字符串s分割成["aa","b"]这样两个回文子串

2.算法

这道题分两步骤完成。

1.找出这个字符串的回文字典dict[i][j],就是字符i到j是否为回文字符串,

2,用动态规划的思想找出字符串的最小分割

    public int minCut(String s)     {        // write your code here    if (s == null || s.length() == 0)    {    return 0;    }    boolean[][] dict = getDict(s);    int[] res = new int[s.length() + 1];    res[0] = 0;    for (int i = 0; i < s.length(); i++) //找到所切得的最小字符串数    {    res[i + 1] = i + 1;    for (int j = 0; j <= i; j++)    {    if (dict[j][i])    {    res[i + 1] = Math.min(res[i + 1], res[j] + 1);    }    }    }    return res[s.length()] - 1;    }    public boolean[][] getDict(String s) //得到回文字典    {    boolean[][] dict = new boolean[s.length()][s.length()];    for (int i = s.length() - 1; i >= 0; i--)    {    for (int j = i; j < s.length(); j++)    {    if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dict[i + 1][j - 1]))    {    dict[i][j] = true;    }    }    }    return dict;    }


0 0