• leetcode — palindrome-partitioning-ii


    import java.util.Arrays;
    
    /**
     *
     * Source : https://oj.leetcode.com/problems/palindrome-partitioning-ii/
     *
     * Given a string s, partition s such that every substring of the partition is a palindrome.
     *
     * Return the minimum cuts needed for a palindrome partitioning of s.
     *
     * For example, given s = "aab",
     * Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
     */
    public class PalindromePartition2 {
    
    
        /**
         * 将字符串分割为多个回文字符串的最小分割次数
         *
         * 定义数组cut[len+1],cut[i]表示从0-的最小分割数,初始化cut[0] = -1,
         * 当i-j是回文字符串的时候,cut[i] = min(cut[i], cut[j]+1)
         *
         * 最后得出的cut[len+1]就是0-(len+1)之间的最小分割数
         *
         * @param str
         * @return
         */
        public int minPartition (String str) {
            if (str.length() <= 1) {
                return 0;
            }
            int[] cut = new int[str.length()+1] ;
            Arrays.fill(cut, Integer.MAX_VALUE);
            boolean[][] table = new boolean[str.length()][str.length()];
            cut[0] = -1;
            for (int i = str.length()-1; i >= 0; i--) {
                for (int j = i; j < str.length(); j++) {
                    if ((i+1 > j - 1 || table[i+1][j-1]) && str.charAt(i) == str.charAt(j)) {
                        table[i][j] = true;
                    }
                }
            }
    
            for (int i = 1; i <= str.length(); i++) {
                for (int j = i-1; j > -1; j--) {
                    if (table[j][i-1]) {
                        cut[i] = Math.min(cut[i], cut[j] + 1);
                    }
                }
            }
    
            return cut[str.length()];
        }
    
        public static void main(String[] args) {
            PalindromePartition2 palindromePartition2 = new PalindromePartition2();
            System.out.println(palindromePartition2.minPartition("aab") + "==1");
        }
    
    }
    
  • 相关阅读:
    Linux文件类型详解
    Linux 基础教程 26-基础网络配置
    Linux 基础教程 25-命令和文件查找
    Bash常用快捷键
    Linux umask权限
    小伙伴们,来关注我吧
    [Selenium With C#基础教程] Lesson-07 复选框
    [Selenium With C#基础教程] Lesson-06 单选按钮
    [Selenium With C#基础教程] Lesson-05 文本框
    [Selenium With C#基础教程] Lesson-04 按钮
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7875263.html
Copyright © 2020-2023  润新知