[Leetcode 131, Medium] Palindrome Partitioning
2015-02-02 13:03
387 查看
Problem:
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
Analysis:
Solution:
C++:
Python:
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"] ]
Analysis:
Solution:
C++:
bool IsPalindrome(const string& str) { for(int begin = 0, end = str.size() - 1; begin < end; ++begin, --end) if(str[begin] != str[end]) return false; return true; } void PopulatePalindromes(string str, vector<string>& partition, vector<vector<string> >& candidates) { for(int i = 1; i <= str.size(); ++i) { string prefix = str.substr(0, i); if(IsPalindrome(prefix)) { partition.push_back(prefix); if(i == str.size()) candidates.push_back(partition); else PopulatePalindromes(str.substr(i), partition, candidates); partition.erase(partition.end() - 1, partition.end()); } } } vector<vector<string> > partition(string s) { vector<vector<string> > candidates; vector<string> partition; PopulatePalindromes(s, partition, candidates); return candidates; }Java:
Python:
相关文章推荐
- [Leetcode 22, Medium] Generate Parentheses
- 【LeetCode】Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层次遍历 - Medium(LinkedIn)
- [LeetCode]131 Palindrome Partitioning
- LeetCode解题报告 55. Jump Game [medium]
- LeetCode-17- Letter Combinations of a Phone Number(查表/递归)-Medium
- LeetCode-22-Generate Parentheses(DFS/递归)-Medium
- LeetCode(131)Palindrome Partitioning
- LeetCode 419. Battleships in a Board (Medium)
- 【LeetCode】236.Lowest Common Ancestor of a Binary Tree(Medium)解题报告
- Leetcode: 515.Find Largest Value in Each Tree Row(Week10, Medium)
- Leetcode 15. 3Sum (Medium) (cpp)
- 【LeetCode】320.Generalized Abbreviation(Medium)解题报告
- Leetcode 134. Gas Station (Medium) (cpp)
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- 题解——Leetcode 241. Different Ways to Add Parentheses 难度:Medium
- Leetcode 452. Minimum Number of Arrows to Burst Balloons[medium]
- 【LeetCode】94.Binary Tree Inorder Traversal(Medium)解题报告
- Leetcode 53. Maximum Subarray (Medium) (cpp)
- 【LeetCode】6.ZigZag Conversion(Medium)解题报告
- Leetcode 238. Product of Array Except Self (Medium) (cpp)