Palindrome Partitioning
来源:互联网 发布:pc1500 水利计算软件 编辑:程序博客网 时间:2024/05/21 11:34
https://oj.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"] ]public List<List<String>> partition(String s)
在正式介绍解法之前,首先想先阐述一个跟palindrome有关的二维DP算法。
f(i,j) = true if i == j
f(i,j) = S[i] == S[j] if i == j - 1
f(i,j) = f(i + 1, j - 1) && S[i] == S[j] if i < j - 1
f(i,j)表示的就是s[i..j]是否为palindrome。
这样就可以用O(N^2)得到这个数组里所有的palindrome,用一个二维数组表示。
代码如下:
boolean[][] dp = new boolean[s.length()][s.length()]; for(int i = 0; i < s.length(); i++) dp[i][i] = true; for(int dist = 1; dist < s.length(); dist++){ for(int i = 0; i < s.length() - dist; i++){ dp[i][i + dist] = s.charAt(i) == s.charAt(i + dist) && (dist == 1 ? true : dp[i + 1][i + dist - 1]); } }
这一题其实就是DFS的暴力递归,除此之外我暂时还想不到别的做法,因为很明显解集的数量上限是指数级的,所以用指数级的算法也应该是可以的。
简单来说就是在每一层保持一个头,然后从头开始循环看头尾之间是否palindrome,是的话就往下递归一层的同时这一层继续循环。其实就是backtrace。代码如下
//high efficiency solution with dp public List<List<String>> partition(String s) { List<List<String>> res = new LinkedList<List<String>>(); boolean[][] dp = new boolean[s.length()][s.length()]; for(int i = 0; i < s.length(); i++) dp[i][i] = true; for(int dist = 1; dist < s.length(); dist++){ for(int i = 0; i < s.length() - dist; i++){ dp[i][i + dist] = s.charAt(i) == s.charAt(i + dist) && (dist == 1 ? true : dp[i + 1][i + dist - 1]); } } Helper(s, 0, new LinkedList<String>(), res, dp); return res; } public void Helper(String s, int start, List<String> cur_res, List<List<String>> res, boolean[][] dp){ if(start == s.length()){ res.add(cur_res); return; } for(int i = start; i < s.length(); i++){ if(dp[start][i]){ List<String> next_res = new LinkedList<String>(cur_res); next_res.add(s.substring(start, i + 1)); Helper(s, i + 1, next_res, res, dp); } } } public boolean isValid(int start, int end, String s){ while(start < end){ if(s.charAt(start) != s.charAt(end)){ return false; } start++; end--; } return true; }
你可以看到我这里放了一个函数isValid,其实在Helper函数中,把dp[start][i]换成isValid(start, i, s)也是可以过的。只是如果套用我刚才的dp算法,效率上会少一个N的倍数。
0 0
- Palindrome partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- Palindrome Partitioning
- 《数据结构编程实验》 1.5.4A Contesting Decision
- oracle中解决被锁定的scott用户的方法。
- 【Unity】查看、使用Untiy内部库和方法
- Ajax使用范例
- Java与数据库对应的日期类型
- Palindrome Partitioning
- HDU 4009 Transfer water(不定根最小树形图)
- 新年快乐
- 黑马程序员——C语言基础---数组、指针
- Linux IPC实践(8) --共享内存/内存映射
- 分水岭算法
- 数据透视表的发明历史
- Linux IPC实践(9) --System V共享内存
- 让你的程序响应再快点