Palindrome Partitioning I, II (DFS, DP) IN THE leetCode solution report)

Source: Internet
Author: User

Question:

Palindrome Partitioning I

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s ="aab",
Return

  [    ["aa","b"],    ["a","a","b"]  ]

Analysis:

Let's get a string, find all the substrings of this string, and all the substrings are input strings, and output their set results.


Solution: (similar to DFS deep traversal !)

String Str = "aab ";

After analyzing the data of the question, we know that the result may be a, a, B, or aa, B!

That is to say, we need to consider I = 1, 2... n, such

Str = "aaa"

Result set

[[A, a, a], [a, aa], [aa, a], [aaa]

Based on this situation, we use a DFS-like algorithm.

Str1 = str. substr (0, I); extract the substring from the beginning of the subscript 0 to the end of the I, and determine whether str1 meets the requirements of the return string,

1. satisfied: in this way, it may become a split case. Therefore, we create a new list set, put str1 into the list, and then find the remaining substring str2 = str in str. substr (I); extract the substring starting from I to the end of the entire string, then use str2 as the new string, and pass the list set to the function for recursive calling. The recursion end condition is that the length of the input string is 0 (this means that it has reached the end of the string). In this case, it is proved that the obtained list set meets the conditions, we add this list set to the result set.

2. If not, continue with I ++ until I = str. length ();

3. After all ends, return the final result set result



AC code:

Package copylist; import java. util. arrayList; public class Solution {/** for external calls **/public ArrayList <String> partition (String s) {ArrayList <String> result = new ArrayList <String> (); ArrayList <String> list = new ArrayList <String> (); if (s = null | s. length () = 0) return result; calResult (result, list, s); return result ;} /*** determine whether a string is a return string * I-> str [0] * j-> s Tr [len-1] * I: Move back * j: Move Forward * @ param str * @ return */private boolean isPalindrome (String str) {int I = 0; int j = str. length ()-1; while (I <j) {if (str. charAt (I )! = Str. charAt (j) {return false;} I ++; j --;} return true;}/***** @ param result: the final result set ArrayList <String> * @ param list: the currently added set ArrayList <String> * @ param str: current String */private void calResult (ArrayList <String> result, ArrayList <String> list, String str) {// when the length of the input string processed is equal to 0, the list of this set meets the conditions and is added to the if (str. length () = 0) result. add (new ArrayList <String> (list); int len = str. length (); // recursive call // After the string goes from, first judge str. whether substring (0, I) is a return string // If yes, continue to call the calResult function and set str. substring (I) String input for processing (int I = 1; I <= len; ++ I) {String subStr = str. substring (0, I); if (isPalindrome (subStr) {list. add (subStr); String restSubStr = str. substring (I); calResult (result, list, restSubStr); list. remove (list. size ()-1) ;}}public static void main (String [] args) {System. out. println (new Solution (). partition ("aabaa "));}}


Question: (DP)

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",
Return1Since the palindrome partitioning["aa","b"]Cocould be produced using 1 cut.


Analysis:

Find the minimum number of splits for the substring set to satisfy a string.

(It has something to do with the previous question. Some cool people on the internet use the DP Method, but we didn't use that method in the previous question, but we need to use DP for this question, otherwise, it will be TLE)


Solution:

We can turn this problem into a problem of dynamic dp planning.


First, we need to define several variables and describe these variables! For ease of understanding, the following are the pseudo code !!!

Len = str. length (); // String length

Int [] cuts = new int [len + 1]; // cuts array, cuts [I] indicates that the substring starting with I and ending with len must reach the minimum cut number required for the question (in this way, the final cuts [0] is the result we want) [initialize cuts [I] = len-I, because in the worst case, the number of substrings starting with I and ending with len must be cut once for each character]

Int [] [] matrix = new int [len] [len]; // you can specify an array of adjacent matrices: for example, matrix [I] [j] = true indicates that sub (I, j) of the substring meets the conditions of the input string!

The conditions for determining whether the matrix [I] [j] meets the input string are:


Matrix [I + 1] [J-1] = true (meaning sub (I + 1, J-1) is a response string) & str [I] = str [j]

Or

J-I <2 & str [I] = str [j] (that is, if j-I = 1, the two characters are equal, if j-I = 0, it is the same character)


In both cases, we set matrix [I] [j] to true to facilitate the next DP, and we can find the minimum cut times.

Cuts [I] = min {cuts [I], cuts [j + 1] + 1}; State Transfer Equation

In this way, the final cuts [0]-1 is the minimum cut count of the string str !!!!


Public class test {public int minCut (String s) {int min = 0; int len = s. length (); boolean [] [] matrix = new boolean [len] [len]; int cuts [] = new int [len + 1]; if (s = null | s. length () = 0) return min; // initialize the value in cuts as the worst case value for (int I = 0; I <len; ++ I) {cuts [I] = len-I;} // dp PROCESS for (int I = len-1; I> = 0; -- I) {for (int j = I; j <len; ++ j) {if (s. charAt (I) = s. charAt (j) & (j-I <2) | (s. charAt (I) = s. charAt (j) & ma Trix [I + 1] [J-1]) {matrix [I] [j] = true; cuts [I] = getMinValue (cuts [I], cuts [j + 1] + 1) ;}} min = cuts [0]; return min-1;} public int getMinValue (int a, int B) {return a> B? B: a;} public static void main (String [] args) {System. out. println (new test (). minCut ("ababbbabbaba "));}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.