LeetCode题解:Palindrome Partitioning
2016-02-09 13:39
232 查看
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”]
]
题意:给定一个字符串,分割字符串使得到的子串都是回文(palindrome)
解决思路:创建一个List<>数组,长度为字符串的长度,数组的索引表示字符串当前长度([0,index])。对该字符串[0,index]求回文子串,最终就能得到结果。
原因在于:长度小于字符串长度的子串的回文子串必然也是原字符串的回文子串。
Return all possible palindrome partitioning of s.
For example, given s = “aab”,
Return
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
题意:给定一个字符串,分割字符串使得到的子串都是回文(palindrome)
解决思路:创建一个List<>数组,长度为字符串的长度,数组的索引表示字符串当前长度([0,index])。对该字符串[0,index]求回文子串,最终就能得到结果。
原因在于:长度小于字符串长度的子串的回文子串必然也是原字符串的回文子串。
public class Solution { public List<List<String>> partition(String s) { int len = s.length(); List<List<String>>[] results = new List[len + 1]; results[0] = new ArrayList<List<String>>(); results[0].add(new ArrayList<String>()); boolean[][] pairs = new boolean[len][len]; for(int i = 0; i < len; i++){ char c = s.charAt(i); results[i + 1] = new ArrayList<List<String>>(); for(int j = 0; j <= i; j++){ if(i == j){ pairs[j][i] = true; }else{ if(s.charAt(j) != c){ continue; } if(j == i - 1){ pairs[j][i] = true; }else{ pairs[j][i] = pairs[j + 1][i - 1]; } } if(pairs[j][i]){ String str = s.substring(j, i + 1); for(List<String> temp : results[j]){ List<String> result = new ArrayList<String>(temp); result.add(str); results[i + 1].add(result); } } } } return results[len]; } }
相关文章推荐
- CSS之定位相关
- bzoj 2324 营救皮卡丘
- CSS之布局相关
- CSS细节之文本换行三属性
- hdu2544 最短路 (floyd)
- Linux学习笔记(五)--用户和用户组管理
- LeetCode题解:Surrounded Regions
- search in rotated sorted array leetcode
- 关键词热度是怎么查的
- LeetCode题解:Longest Consecutive Sequence
- 欢迎使用CSDN-markdown编辑器
- 分数拆分
- LSM和B+树区别
- Ubuntu下Qt无法加载Help模块的解决办法
- 5、聚类之层次聚类、基于划分的聚类(k-means)、基于密度的聚类、基于模型的聚类
- Codeforces Round #311 (Div. 2)
- NOI国家集训队论文分类(至2008)
- spark源码学习(二)---Master源码分析(2)-master内组件状态改变机制
- 简单说说glutGet(GLUT_WINDOW_X/Y)与glViewport
- 微信红包随机算法 OC