标签:回文 palindrome partition 面试 leetcode algorithm
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"] ]
回文划分,题目意思是给一个字符串,找出将字符串划分为一系列回文子串的各种可能组合。例如,一个子串“aab“,你需要返回["aa","b"],["a","a","b"]。这个题目的解法也是非常的典型---循环加递归,这是解决组合排列问题的标准解法。Leetcode上面还有许多这种解法的题目。
对于aab:
判断a,再判断ab;
ab:先判断a,在判断b;
b:判断完,结束
判断aa,再判断b
b:判断完,结束
其余的看代码理解吧。
class Solution { public: vector<vector<string> > partition(string s) { vector<vector<string> > ret; vector<string> part; helper(0, s, part, ret); return ret; } void helper(int start, const string &s, vector<string> part, vector<vector<string> > &ret){ int n = s.size(); if(start == n){ ret.push_back(part); return ; } for(int i=start; i<n; ++i){ string temp = s.substr(start, i-start+1); if( !validPalindrome(temp)) continue; part.push_back(temp); helper(i+1, s, part, ret); part.pop_back(); } } bool validPalindrome(string s){ int begin = 0, end = s.size()-1; while(begin<end){ if(s[begin] != s[end]) return false; ++begin, --end; } return true; } };
[LeetCode] Palindrome Partition [11],布布扣,bubuko.com
[LeetCode] Palindrome Partition [11]
标签:回文 palindrome partition 面试 leetcode algorithm
原文地址:http://blog.csdn.net/swagle/article/details/28889301