首页 > 代码库 > [leetcode-131-Palindrome Partitioning]
[leetcode-131-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 = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
思路:
回溯法。注意随时判断子字符串是否是回文串。
bool isPali(string s) { int len = s.length(); for (int i = 0; i <= s.length()/2;i++) { if (s[i] != s[len - i - 1])return false; } return true; } void parti(vector<vector<string>>& res, vector<string>& pal,string s,int begin) { if (begin>=s.length()) { res.push_back(pal); return; } for (int i = begin; i < s.length();i++) { if (isPali(s.substr(begin,i-begin+1))) { pal.push_back(s.substr(begin, i - begin + 1));// pal.push_back(s.substr(i, i - begin + 1));这样不对 parti(res, pal, s, i + 1); pal.pop_back(); } } } vector<vector<string>> partition(string s) { vector<vector<string>> res; if (s.empty())return res; vector<string> pal; parti(res, pal, s, 0); return res; }
[leetcode-131-Palindrome Partitioning]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。