LeetCode刷題實戰131:分割回文串

算法的重要性,我就很少說了吧,想去大廠,就必需要通過基礎知識和業務邏輯面試+算法面試。因此,爲了提升你們的算法能力,這個公衆號後續天天帶你們作一道算法題,題目就從LeetCode上面選 !今天和你們聊的問題叫作 分割回文串,咱們先來看題面:https://leetcode-cn.com/problems/palindrome-partitioning/

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.面試

 

A palindrome string is a string that reads the same backward as forward.算法

題意

給定一個字符串 s,將 s 分割成一些子串,使每一個子串都是迴文串。返回 s 全部可能的分割方案。

 

樣例

示例:

輸入: "aab"
輸出:
[
  ["aa","b"],
  ["a","a","b"]
]ide

解題

https://www.jianshu.com/p/e1017e1674ea這是一道很綜合的題目,結合了動態規劃,深度搜索和回溯法。首先爲了分割出迴文串,咱們首先要寫出判斷迴文串的方法,這裏使用動態規劃來判斷迴文串,並且能夠存儲子串的迴文串的狀況。isPalindrome[i][j]:表示i到j的子串是不是迴文串。狀態轉移方程:isPalindrome[i][j] = isPalindrome[i+1][j-1] && s.charAt(i) == s.charAt(j)天然若是一個串是迴文串,那麼首尾必需要相等,而且中間也是子串。初始化,顯然當i==j的時候都是迴文串當串只有兩個字符且相等的時候也是迴文串。知道如何判斷子串是不是迴文串就好辦了,而後只要模式化的深度搜索回溯便可 。public class Solution {     /**      * @param s: A string      * @return: A list of lists of string      */          List<List<String>> results;     boolean[][] isPalindrome;          /**      * @param s: A string      * @return: A list of lists of string      */     public List<List<String>> partition(String s) {         results = new ArrayList<>();         if (s == null || s.length() == 0) {             return results;         }                  getIsPalindrome(s);                  helper(s, 0, new ArrayList<Integer>());                  return results;     }          private void getIsPalindrome(String s) {         int n = s.length();         isPalindrome = new boolean[n][n];                  for (int i = 0; i < n; i++) {             isPalindrome[i][i] = true;         }         for (int i = 0; i < n - 1; i++) {             isPalindrome[i][i + 1] = (s.charAt(i) == s.charAt(i + 1));         }                  for (int i = n - 3; i >= 0; i--) {             for (int j = i + 2; j < n; j++) {                 isPalindrome[i][j] = isPalindrome[i + 1][j - 1] && s.charAt(i) == s.charAt(j);             }         }     }          private void helper(String s,                         int startIndex,                         List<Integer> partition) {         if (startIndex == s.length()) {             addResult(s, partition);             return;         }                  for (int i = startIndex; i < s.length(); i++) {             if (!isPalindrome[startIndex][i]) {                 continue;             }             partition.add(i);             helper(s, i + 1, partition);             partition.remove(partition.size() - 1);         }     }          private void addResult(String s, List<Integer> partition) {         List<String> result = new ArrayList<>();         int startIndex = 0;         for (int i = 0; i < partition.size(); i++) {             result.add(s.substring(startIndex, partition.get(i) + 1));             startIndex = partition.get(i) + 1;         }         results.add(result);     } }好了,今天的文章就到這裏,若是以爲有所收穫,請順手點個在看或者轉發吧,大家的支持是我最大的動力。