LeetCode题解:Palindrome Partitioning
来源:互联网 发布:编程差可以做it运维吗 编辑:程序博客网 时间:2024/05/07 09:06
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]求回文子串,最终就能得到结果。
原因在于:长度小于字符串长度的子串的回文子串必然也是原字符串的回文子串。
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]; }}
0 0
- LeetCode题解:Palindrome Partitioning
- Palindrome Partitioning II|leetcode题解
- LeetCode - Palindrome Partitioning II 题解
- LeetCode 题解(90): Palindrome Partitioning II
- LeetCode 题解(152): Palindrome Partitioning
- 【leetcode题解】【M】【79】Palindrome Partitioning
- LeetCode题解–131. Palindrome Partitioning
- 【leetcode】Palindrome Partitioning && Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning && Palindrome Partitioning II
- LeetCode Palindrome Partitioning I&&Palindrome Partitioning II
- LeetCode Palindrome Partitioning, Palindrome Partitioning II
- [Leetcode][python]Palindrome Partitioning/Palindrome Partitioning II
- Leetcode:Palindrome Partitioning & Palindrome Partitioning II
- LeetCode: Palindrome Partitioning
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode 122: Palindrome Partitioning
- leetcode:Palindrome Partitioning II
- bzoj 2324 营救皮卡丘
- CSS之布局相关
- 104. Maximum Depth of Binary Tree LeetCode
- CSS之定位相关
- 加强调查取证,夯实威胁情报基础
- LeetCode题解:Palindrome Partitioning
- CSS之动效相关
- CSS之特殊相关
- CSS之显示相关
- CSS之选择器相关
- CSS之样式相关
- UVa--129 Krypton Factor(DFS)
- c语言 删除字符串
- 【第二章】 IoC 之 2.3 IoC的配置使用——跟我学Spring3