131Palindrome Partitioning

来源:互联网 发布:唐山震后重建数据 编辑:程序博客网 时间:2024/06/16 06:17

题目链接:https://leetcode.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.For example, given s = "aab",Return  [    ["aa","b"],    ["a","a","b"]  ]

解题思路:
这题自己没想出来,参考了大神的思路。
1. 首先根据 Longest Palindromic Substring 中的方法建立一个字典,得到字符串中的任意子串是不是回文串的字典
2. 接下来就跟 Word Break II 一样,根据字典的结果进行切割,然后按照循环处理递归子问题的方法
3. 如果当前的子串满足回文条件,就递归处理字符串剩下的子串
4. 如果到达终点就返回当前结果

代码实现:

public class Solution {    public List<List<String>> partition(String s) {        List<List<String>> res = new ArrayList();        if(s == null || s.length() == 0)            return res;        helper(s, getDict(s), 0, new ArrayList<String>(), res);        return res;    }    void helper(String s, boolean[][] dict, int start, List<String> item, List<List<String>> res) {        if(start == s.length()) {            res.add(new ArrayList(item));            return;        }        for(int i = start; i < s.length(); i ++) {            if(dict[start][i]) {                item.add(s.substring(start, i + 1));                helper(s, dict, i + 1, item, res); // 以 i 的下一个位置为起点,查看后面是否有回文                item.remove(item.size() - 1);            }        }    }    boolean[][] getDict(String s) {        boolean[][] dict = new boolean[s.length()][s.length()];        for(int i = s.length() - 1; i >= 0; i --) {            for(int j = i; j < s.length(); j ++) {                if(s.charAt(i) == s.charAt(j) && (j - i < 2 || dict[i + 1][j - 1])) // 这个判断条件用个例子就可以理解                    dict[i][j] = true;            }        }        return dict;    }}
21 / 21 test cases passed.Status: AcceptedRuntime: 8 ms
0 0
原创粉丝点击