lintode(108)分割回文串 II

来源:互联网 发布:js里能生成uuid吗 编辑:程序博客网 时间:2024/05/17 23:12

描述:

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

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


样例:

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

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


思路:

eg:aabbaac

首先确定从s[i]到s[j]是否为回字符串

 aabbaacaTTFFFTFa TFFTFFb  TTFFFb   TFFFa    TTFa     TFc      T

然后统计最小分割次数:

 0123456result1322110

public class Solution {    /**     * @param s a string     * @return an integer     */    public int minCut(String s) {        // write your code here        if(s == null || s.length() == 0){            return 0;        }        int len = s.length();        int[] result = new int[len];        boolean[][] whether = new boolean[len][len];        search(whether , s);        for(int i = len - 1;i>=0;i--){            if(whether[i][len - 1]){                result[i] = 0;                continue;            }            result[i] = len - 1;            for(int j = i+1;j<len;j++){                if(whether[i][j - 1]){                    result[i] = Math.min(result[i] , result[j] + 1);                }            }        }        return result[0];    }        public void search(boolean[][] whether , String s){        for(int l = 1 ; l<= s.length();l++){            for(int i = 0;i <= s.length() - l;i++){                int j = i + l -1;                if(l == 1){                    whether[i][j] = true;                }else if(l == 2){                    whether[i][j] = (s.charAt(i) == s.charAt(j));                }else{                    whether[i][j] = (s.charAt(i) == s.charAt(j)) && whether[i+1][j-1];                }            }        }    }};


0 0
原创粉丝点击