-
Notifications
You must be signed in to change notification settings - Fork 2
/
Palindrome Partitioning
43 lines (40 loc) · 1.14 KB
/
Palindrome Partitioning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> ans;
backTrack(0,s,ans,result);
return result;
}
void backTrack(int m,string s,vector<string>&ans,vector<vector<string>>&result)
{
if(m==s.size())
{
result.push_back(ans);
}
else
{
for(int i = m;i<s.size();i++)
{
//be careful to take the substring
string sub_str = s.substr(m,i-m+1);
//cout << "sub_str=" << sub_str << endl;
if(isPalindrome(sub_str))
{
ans.push_back(sub_str);
backTrack(i+1,s,ans,result);
ans.pop_back();
}
}
}
}
bool isPalindrome(string s) {
int start = 0, end = s.size()-1;
while(start<end)
{
if(tolower(s[start++]) != tolower(s[end--]))
return false; // return false when nonequal is found
}
return true;
}
};