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.用回溯,递归回溯超时

    2.dp

    这里需要两个dp状态数组

    isPalin[i][j] = true表示字符串str.sub(i, j)为回文

    递推关系式isPalin[i][j] = (str.charAt(i) == str.charAt(j) && j -i < 2) || (str.charAt(i) == str.charAt(j) && isPalin[i + 1][j - 1])

    cuts[i]表示从第str.charAt(i)到str.length()需要多少cut。默认为每个字符都切一刀,即cuts[i] = str.length - i。递推关系

    if(isPalin[i][j])

      cuts[i] = min{cuts[i], cuts[i + j] + 1}

    参考:http://blog.csdn.net/ljphhj/article/details/22573983

     1 public class Solution {
     2     public int minCut(String s) {
     3         int min = 0;
     4         if(0 == s.length() || 1 == s.length())
     5             return min;
     6         boolean isPalin[][] = new boolean[s.length()][s.length()];
     7         int cuts[] = new int[s.length() + 1];
     8         int length = s.length();
     9         
    10         //初始化cuts[]数组
    11         for(int i = 0; i < length; i++)
    12             cuts[i] = length - i;
    13         //dp过程
    14         for(int i = length - 1; i >= 0; i--){
    15             for(int j = i; j < length; j++){
    16                 if((s.charAt(i) == s.charAt(j) && (j - i < 2))
    17                         || (s.charAt(i) == s.charAt(j) && isPalin[i + 1][j - 1])){
    18                     isPalin[i][j] = true;
    19                     cuts[i] = getMin(cuts[i], cuts[j + 1] + 1);
    20                 }//if
    21             }//for
    22         }//for
    23         
    24         min = cuts[0];
    25         
    26         return min - 1;
    27     }//minCut
    28     
    29     public int getMin(int num1, int num2){
    30         return num1 < num2 ? num1 : num2;
    31     }
    32 }
  • 相关阅读:
    注释
    Servlet原理和开发
    什么是Servlet
    Java基础目录
    实现第一个Servlet
    Servlet的体系
    习题3
    利用ResultFilter实现asp.net mvc3 页面静态化
    oracle欲出纯托管代码的ODP.NET,现接受小范围预览版本使用申请
    http请求头中包含未编码中文时webapi self host崩溃
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4271817.html
Copyright © 2011-2022 走看看