您的位置:首页 > 其它

Palindrome Partitioning

2013-07-25 14:10 127 查看

题目

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"]
]

思路

类似于 排列组合思想。

其中是否是有效的回文,可以参考博文 valid palindrome

class Solution {
public:
vector<vector<string>> partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = s.length();
vector<vector<string> > result;
if(len<1) return result;
vector<string> vec;
mypart(result, vec, 0, s);
return result;
}
void mypart(vector<vector<string>> &result, vector<string> &vec, int cur, string &S) {
if(cur==S.length()) {
result.push_back(vec);
return ;
}
for(int i=cur;i<S.length();i++) {
int len = i-cur+1;
string str = S.substr(cur,len);
if(ispalind(str)) {
vec.push_back(str);
mypart(result, vec, i+1, S);
vec.pop_back();
}
}
}

bool ispalind(string &S) {
if(S.empty())
return true;
int i=0, j=S.length()-1;
while(i<j) {
if(S[i]!=S[j])
return false;
i++;
j--;
}
return true;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息