leetcode:Palindrome Partitioning
来源:互联网 发布:js class隐藏元素 编辑:程序博客网 时间:2024/06/06 22:39
给出一个字符串s,返回他所有可能的回文字符串集合
假设对于任何字符串s0s1s2-sk, 存在si-sk是回文字符串,那么他可能的回文集合就是{s0si-1}的方案+si-sk
为了方便回溯,我们先对其进行预处理,让dp[i][j]表示字符串i-j是否回文串
那么容易推出
dp[i][j] = dp[i+1]dp[j - 1] && s[i] == s[j];
public class Solution { static ArrayList<String> stack = new ArrayList<String>(); static ArrayList<ArrayList<String>> ans = new ArrayList<ArrayList<String>>(); static char[] str; public ArrayList<ArrayList<String>> partition(String s) { boolean[][] dp = new boolean[s.length()][s.length()]; str = s.toCharArray(); for (int k = 0; k < s.length(); ++k) { for (int i = 0; i < s.length() && i + k < s.length(); ++i) { // if(k <= 1){ // dp[i][i + k] = s.charAt(i) == s.charAt(i + k); // }else{ // dp[i][i + k] = s.charAt(i) == s.charAt(i + k) && dp[i + 1][i + k - 1]; // } dp[i][i + k] = s.charAt(i) == s.charAt(i + k) && (k <= 1 || dp[i + 1][i + k - 1]); } } stack.clear(); ans.clear(); dfs(dp, 0); return ans; } public static void dfs(boolean[][] dp, int index){ if(index >= dp.length){ ArrayList<String> t = new ArrayList<String> (); for(int i = 0; i < stack.size(); ++i){ t.add(stack.get(i)); } ans.add(t); } else{ for(int i = index; i < dp.length; ++i){ if(dp[index][i] == true){ String t = new String(str, index, i - index + 1); stack.add(t); dfs(dp, i + 1); stack.remove(stack.size() - 1); } } } } }
0 0
- 【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
- leetcode:Palindrome Partitioning
- 【leetcode】Palindrome Partitioning
- 【leetcode】Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- Leetcode - Palindrome Partitioning
- LeetCode之Palindrome Partitioning
- [LeetCode]Palindrome Partitioning
- Hibernate进阶之双向一对一关系映射
- 线程笔记
- 数据结构课程设计题目十二_计算机学院学生会的打印机(优先队列)
- struts2配置加实现
- 令人敬畏的泰格伍兹
- leetcode:Palindrome Partitioning
- codeforce 14C
- postgrepsql数据库安装配置使用
- Linux内核设计基础(十)之内核开发与总结
- 基于粒子滤波器的目标跟踪算法及实现
- 关于权限管理的demo
- FIQ和IRQ区别
- c++面试题之 找出字符串中第一个只出现一次的字符
- Spring3学习