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/

  • 相关阅读:
    oracle 将以逗号分隔的列拆成多行的的方法
    Oracle 如何循环查询结果集,进行新增或修改
    CSS 属性 伪类和伪元素的区别
    正则应用—queryURLParameter()
    老式浏览器兼容HTML5和CSS3的问题
    CSS3 常用新特性总结
    移动web资源整理
    移动webApp 1像素实现(点5像素的秘密)
    Git常用命令总结
    undefined与null的区别
  • 原文地址:https://www.cnblogs.com/hygeia/p/4834112.html
Copyright © 2011-2022 走看看