lintcode-medium-Palindrome Partition II
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Palindrome Partition II相关的知识,希望对你有一定的参考价值。
Given a string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example
Given s = "aab"
,
Return 1
since the palindrome partitioning ["aa", "b"] could be produced using1 cut.
public class Solution { /** * @param s a string * @return an integer */ public int minCut(String s) { // write your code here if(s == null || s.length() == 0) return 0; int len = s.length(); boolean[][] isPalindrome = new boolean[len][len]; for(int i = 0; i < len; i++){ isPalindrome[i][i] = true; } for(int i = 0; i < len - 1; i++) isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1)); for(int i = len - 1; i >= 0; i--){ for(int j = i + 2; j < len; j++){ if(s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1]) isPalindrome[i][j] = true; else isPalindrome[i][j] = false; } } if(isPalindrome[0][len - 1]) return 0; int[] f = new int[s.length()]; for (int i = 0; i < s.length(); i++) { f[i] = i; } for (int i = 0; i < s.length(); i++) { if(isPalindrome[0][i]) f[i] = 0; else for (int j = 0; j < i; j++) if(isPalindrome[j + 1][i]) f[i] = Math.min(f[i], f[j] + 1); } return f[len - 1]; } public boolean valid(String s){ int left = 0; int right = s.length() - 1; while(left < right){ if(s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } };
以上是关于lintcode-medium-Palindrome Partition II的主要内容,如果未能解决你的问题,请参考以下文章