Leetcode 131. Palindrome Partitioning
来源:互联网 发布:知乎b站三国演义 编辑:程序博客网 时间:2024/06/11 01:19
DFS non-DP solution.
public class Solution { public List<List<String>> partition(String s) { List<List<String>> ret = new ArrayList<>(); List<String> curr = new ArrayList<>(); dfs(0, s, curr, ret); return ret; } private static void dfs(int pos, String s, List<String> curr, List<List<String>> ret) { if (pos == s.length()) { ret.add(new ArrayList<>(curr)); return; } for (int i=pos; i<s.length(); i++) { String subStr = s.substring(pos, i+1); if (isPalindrome(subStr)) { curr.add(subStr); dfs(i+1, s, curr, ret); curr.remove(curr.size()-1); } } } private static boolean isPalindrome(String s) { int i=0, j=s.length()-1; while (i < j) { if (s.charAt(i) != s.charAt(j)) { return false; } i++; j--; } return true; }}Improvement (from 13ms to 7ms). Using a 2D array to save if substring(i, j+1) is a palindrom so that we don't need to check isPalindorme(substring(i, j+1)) every time we call DFS.
public class Solution { public List<List<String>> partition(String s) { boolean[][] dp = new boolean[s.length()][s.length()]; buildPalinTab(dp, s); List<List<String>> ret = new ArrayList<>(); List<String> curr = new ArrayList<>(); dfs(0, s, curr, ret, dp); return ret; } private static void dfs(int pos, String s, List<String> curr, List<List<String>> ret, boolean[][] dp) { if (pos == s.length()) { ret.add(new ArrayList<>(curr)); return; } for (int i=pos; i<s.length(); i++) { if (dp[pos][i]) { String subStr = s.substring(pos, i+1); curr.add(subStr); dfs(i+1, s, curr, ret, dp); curr.remove(curr.size()-1); } } } private static void buildPalinTab(boolean[][] dp, String s) { for (int i=s.length()-1; i>=0; i--) { for (int j=i; j<s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { if (j-i < 3) dp[i][j] = true; else dp[i][j] = dp[i+1][j-1]; } } } }}
0 0
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- 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
- Leetcode-131. Palindrome Partitioning
- 【LeetCode】131. Palindrome Partitioning
- Leetcode 131. Palindrome Partitioning
- 关于P、NP问题和算法的一点联系
- #6. ZigZag Conversion
- 快速幂及其简单应用
- 1st round, 91 Decode Ways
- Java_每天学习一点点之基本结构
- Leetcode 131. Palindrome Partitioning
- 107. Binary Tree Level Order Traversal II
- 102. Binary Tree Level Order Traversal
- Leetcode 211. Add and Search Word - Data structure design
- 布尔巴基的学术风格
- T-SQL 语句(一)—— 数据库操作
- Leetcode 213. House Robber II
- Leetcode 47. Permutations II
- 快速排序算法浅析