LeetCode(Palindrome Partitioning) 将字符串分割成回文字符串
2014-04-08 10:51
411 查看
题目要求:
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"] ]
思路: 递归枚举。
代码:
class Solution { public: vector<vector<string> > ans; //判断是不是回文 bool IsPalindrome(const string& str, int start, int end) { if (start == end) { return true; } while (start < end) { if(str[start] != str[end]) return false; ++start; --end; } return true; } void RecursivePartiton(string& s, int start, vector<string>& par) { if(start == s.size()) { ans.push_back(par); return; } for(size_t i = start; i < s.size(); ++i) { //如果start 到 i是回文,则将其分割,从下个位置i+1起继续递归分割 if (IsPalindrome(s, start, i)) { par.push_back(s.substr(start, i - start + 1)); RecursivePartiton(s, i + 1, par); par.pop_back();//递归回溯 } } } vector<vector<string> > partition(string s) { vector<string> par; par.clear(); ans.clear(); RecursivePartiton(s, 0, par); return ans; } };
相关文章推荐
- Palindrome Partitioning 分割字符串为回文@LeetCode
- [LeetCode] Valid Palindrome II 验证回文字符串之二
- Leetcode 131 Palindrome Partitioning 回文分割
- leetcode 151. Reverse Words in a String 字符串分割逆序 + stringstream分割字符串
- leetcode125---Valid Palindrome(回文字符串)
- LeetCode之“字符串”:最短回文子串
- 【leetcode】第5题:找出字符串中最长的回文字符串
- leetcode 5 Longest Palindromic Substring--最长回文字符串
- [LeetCode] Split Concatenated Strings 分割串联字符串
- 求回文字符串的最小分割
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- 判断字符串是否能分割成字典中的单词(二)——Leetcode系列(十二)
- 分割成回文需要的最小分割数 Palindrome Partitioning II @LeetCode
- leetcode 5 Longest Palindromic Substring--最长回文字符串
- leetcode 434. Number of Segments in a String 按照空格分割字符串 + C++的stringstream的一个很好应用示范
- LeetCode OJ 之 Palindrome Partitioning (字符串的回文分割)
- leetcode 5 Longest Palindromic Substring--最长回文字符串
- [LeetCode 132] - 回文分割II(Palindrome Partitioning II)
- [LeetCode] 131. Palindrome Partitioning 回文分割
- [网易]字符串回文分割