zoukankan      html  css  js  c++  java
  • **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.

     1 public class Solution {
     2     private boolean isPalindrome(String s, int start, int end) {
     3         for (int i = start, j = end; i < j; i++, j--) {
     4             if (s.charAt(i) != s.charAt(j)) {
     5                 return false;
     6             }
     7         }
     8         return true;
     9     }
    10 
    11     private boolean[][] getIsPalindrome(String s) {
    12         boolean[][] isPalindrome = new boolean[s.length()][s.length()];
    13 
    14         for (int i = 0; i < s.length(); i++) {
    15             isPalindrome[i][i] = true;
    16         }
    17         for (int i = 0; i < s.length() - 1; i++) {
    18             isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));
    19         }
    20 
    21         for (int length = 2; length < s.length(); length++) {
    22             for (int start = 0; start + length < s.length(); start++) {
    23                 isPalindrome[start][start + length]
    24                     = isPalindrome[start + 1][start + length - 1] && s.charAt(start) == s.charAt(start + length);
    25             }
    26         }
    27 
    28         return isPalindrome;
    29     }
    30 
    31     public int minCut(String s) {
    32         if (s == null || s.length() == 0) {
    33             return 0;
    34         }
    35 
    36         // preparation
    37         boolean[][] isPalindrome = getIsPalindrome(s);
    38         
    39         // initialize
    40         int[] f = new int[s.length() + 1];
    41         for (int i = 0; i <= s.length(); i++) {
    42             f[i] = i - 1;
    43         }
    44         
    45         // main
    46         for (int i = 1; i <= s.length(); i++) {
    47             for (int j = 0; j < i; j++) {
    48                 if (isPalindrome[j][i - 1]) {
    49                     f[i] = Math.min(f[i], f[j] + 1);
    50                 }
    51             }
    52         }
    53 
    54         return f[s.length()];
    55     }
    56 }

    reference: http://www.jiuzhang.com/solutions/palindrome-partitioning-ii/

  • 相关阅读:
    解决mysqldump: Got error: 1044: Access denied for user
    Ubuntu技巧之 is not in the sudoers file解决方法
    mysql日志详细解析
    linux利用grep查看打印匹配的下几行或前后几行的命令
    Linux无法使用userdel删除用户和组的解决办法
    ubuntu快速清理磁盘垃圾
    smarty中math函数的用法
    metinfo首页内容简介
    linux命令别名的使用
    mysql 导出表结构和表数据 mysqldump用法
  • 原文地址:https://www.cnblogs.com/hygeia/p/4834112.html
Copyright © 2011-2022 走看看