LeetCode 131. Palindrome Partitioning(回文分区)
2016-05-27 00:25
483 查看
原题网址:https://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 =
Return
方法:深度优先搜索。
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 class Solution { private List<List<String>> results = new ArrayList<>(); private boolean[][] palindrome; private void find(String s, List<String> partition, int from) { if (from == s.length()) { List<String> result = new ArrayList<>(); result.addAll(partition); results.add(result); return; } for(int i=0; from+i<s.length(); i++) { if (!palindrome[i][from]) continue; partition.add(s.substring(from, from+i+1)); find(s, partition, from+i+1); partition.remove(partition.size()-1); } } public List<List<String>> partition(String s) { if (null == s || "".equals(s)) return results; palindrome = new boolean[s.length()][s.length()]; for(int i=0; i<s.length(); i++) { for(int j=0; j+i<s.length(); j++) { if (i==0) { palindrome[i][j] = true; } else if (i==1) { if (s.charAt(j) == s.charAt(j+i)) { palindrome[i][j] = true; } else { palindrome[i][j] = false; } } else { if (palindrome[i-2][j+1] && s.charAt(j) == s.charAt(j+i)) { palindrome[i][j] = true; } else { palindrome[i][j] = false; } } } } find(s, new ArrayList<>(), 0); return results; } }
相关文章推荐
- LeetCode 130. Surrounded Regions(包围区域)
- Linux下客户端主动Close,服务端阻塞的read函数不会马上返回
- 使用Consul打造弹性可扩展的PaaS平台
- 安卓入门--Sqlite安卓中数据库的增删查改
- 一个脚本安装mysql
- 非table 布局 重叠边框合并方法
- LeetCode 141. Linked List Cycle(链表循环)
- LeetCode 140. Word Break II(单词切分)
- LeetCode 139. Word Break(单词分隔)
- LeetCode 138. Copy List with Random Pointer(拷贝随机指针)
- LeetCode 137. Single Number II(单个数字)
- LeetCode 136. Single Number(单个数字)
- LeetCode 135. Candy(糖果)
- LeetCode 134. Gas Station(加油站)
- LeetCode 132. Palindrome Partitioning II(回文切分)
- LeetCode 133. Clone Graph(克隆图)
- 原型链(__proto__)
- makefile之VPATH和vpath的使用
- System.in.read()
- javascript的 Object 和 Function