Palindrome Partitioning
来源:互联网 发布:淘宝双11怎么修改价格 编辑:程序博客网 时间:2024/05/20 18:48
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example
Given s = "aab"
, return:
[ ["aa","b"], ["a","a","b"]]
java
public class Solution { /* * @param s: A string * @return: A list of lists of string */ public List<List<String>> partition(String s) { // write your code here List<List<String>> result = new ArrayList<>(); if (s == null || s.length() == 0) { return result; } List<String> list = new ArrayList<>(); if (s.length() == 1) { list.add(s); result.add(list); return result; } dfs(s, 0, list, result); return result; } private void dfs(String s, int startIndex, List<String> list, List<List<String>> result) { if (startIndex == s.length()) { result.add(new ArrayList<String>(list)); } for (int i = startIndex; i < s.length(); i++) { String sub = s.substring(startIndex, i + 1); if (!isPalindrome(sub)) { continue; } else { list.add(sub); dfs(s, i + 1, list, result); list.remove(list.size() - 1); } } } private boolean isPalindrome(String s) { if (s == null || s.length() == 0) { return false; } char[] c = s.toCharArray(); int i = 0; int j = c.length - 1; while (i <= j) { if (c[i++] != c[j--]) { return false; } } return true; }}
python
class Solution: """ @param: s: A string @return: A list of lists of string """ def partition(self, s): # write your code here if s is None or len(s) == 0: return [[]] result = [] self.dfs(s, 0, [], result) return result def dfs(self, s, startIndex, arr, result): if startIndex > len(s): return if startIndex == len(s): result.append(list(arr)) for i in range(startIndex, len(s)): sub = s[startIndex: i + 1] if not self.isPalindrome(sub): continue else: arr.append(sub) self.dfs(s, i + 1, arr, result) arr.pop() def isPalindrome(self, s): if s is None: return False if len(s) == 1: return True start, end = 0, len(s) - 1 while start <= end: if s[start] != s[end]: return False else: start += 1 end -= 1 return True
阅读全文
1 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
- jQuery操作表格(table)的常用方法、技巧汇总
- Java 中的方法内部类
- Python篇(一):ubuntu14.04下Python的环境配置
- 基于MFC的五子棋应用(四)实践
- dpdk vhost研究 (三)
- Palindrome Partitioning
- ConcurrentHashMap
- 《图解HTTP》读书笔记(1)之第一章了解Web及网络基础(关键词:计算机网络/HTTP/Web/网络基础)
- setTimeout与console.log之间执行先后顺序
- Linux中线程栈测试
- 【Java】实现浮点数组的并集以及整型数组的交集和两个字符串数组的逆序排序
- servlet实现秒数跳转操作的源码
- 归并排序
- Centos6.4下搭建redis缓存