zoukankan      html  css  js  c++  java
  • LeetCode 132 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.推断字符串的字串S.subString(i,j) [i<=j]是否为为回文子串,用boolean型的二维数组isPalindrome来存储该结果

    在这个地方用了点小技巧,isPalindrome[i]j]会依赖于sPalindrome[i+1]j-1]  [i+2<=j].
               2.使用动态规划的思想,若S.subString(i,j) 是回文字符串,则仅仅要看 ans[i] - 1 > ans[j - 1]是否成立,若成立,则更新他

    public class Solution {
    	public int minCut(String s) {
    		int[] ans = new int[s.length()];
            boolean[][] isPalindrome = new boolean[s.length()][s.length()];
            for (int i = 0; i < s.length(); i++) 
                isPalindrome[i][i] = true;
            
            for (int i = 0; i < s.length() - 1; i++) 
                isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));
            
    
            for (int length = 2; length < s.length(); length++) {
                for (int start = 0; start + length < s.length(); start++) {
                    isPalindrome[start][start + length]
                        = isPalindrome[start + 1][start + length - 1] && s.charAt(start) == s.charAt(start + length);
                }
            }
            
    		for (int i = 1; i < s.length(); i++) {
    			if (isPalindrome[0][i])
    				continue;
    			ans[i] = Integer.MAX_VALUE;
    			for (int j = 1; j <= i; j++) {
    				if (isPalindrome[j][i] && ans[i] - 1 > ans[j - 1]) {
    					ans[i] = 1 + ans[j - 1];
    				}
    			}
    		}
    		return ans[s.length() - 1];
    	}
    }


  • 相关阅读:
    S2T40,第五章
    S2T40,第四章,简答5
    sqlmap扫描发现注入点示例
    使用jenkins部署.net项目
    在线预览PDF插件
    Visual Studio 2019 License Key
    asp.net core mvc 中 ModelState.IsValid 值是fasle
    sql操作
    sql server 查找与替换 正则表达式 匹配
    asp.net redis 帮助类封装
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7080416.html
Copyright © 2011-2022 走看看