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
- LeetCode: Palindrome Partitioning [131]
- LeetCode 131 Palindrome Partitioning
- LeetCode(131)Palindrome Partitioning
- [leetcode 131] Palindrome Partitioning
- [leetcode]131 Palindrome Partitioning
- LeetCode 131 Palindrome Partitioning
- leetcode ||131、Palindrome Partitioning
- LeetCode(131) Palindrome Partitioning
- leetcode 131: Palindrome Partitioning
- Leetcode #131 Palindrome Partitioning
- 131 Palindrome Partitioning
- 131 Palindrome Partitioning [Leetcode]
- LeetCode 131 Palindrome Partitioning
- 131Palindrome Partitioning
- Leetcode 131:Palindrome Partitioning
- 【LeetCode-131】Palindrome Partitioning
- Leetcode 131 Palindrome Partitioning
- [leetCode 131]Palindrome Partitioning
- Centos开发环境搭建
- alpha透明
- java笔记 第四章 Java面向对象编程基础第一部分(类和main方法)
- 软姐之机器学习讲义
- iOS AFN下载
- 131Palindrome Partitioning
- linux命令学习(4)
- JavaScript-CheckBox全选/反选
- poj1005 I Think I Need a Houseboat 水题
- python基础(二)
- 第三天
- NOIP2014 Day1T3 飞扬的小鸟 dp
- Python写爬虫——抓取网页并解析HTML
- iOS 实现打印功能