This repository has been archived by the owner on Dec 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 366
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #303 from rakshil14-2/patch-1
Create palindromicpartion.cpp
- Loading branch information
Showing
1 changed file
with
97 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
//{ Driver Code Starts | ||
// Initial Template for c++ | ||
|
||
#include <bits/stdc++.h> | ||
using namespace std; | ||
|
||
// } Driver Code Ends | ||
// User function Template for C++ | ||
|
||
class Solution{ | ||
public: | ||
int t[501][501]; | ||
bool palindrome(string s1,int i ,int j) | ||
{ | ||
|
||
if(i==j) | ||
return true; | ||
if(i>j) | ||
return true; | ||
|
||
while(i<j) | ||
{ | ||
if(s1[i]!=s1[j]) | ||
return false; | ||
|
||
i++; | ||
j--; | ||
} | ||
return true; | ||
|
||
} | ||
|
||
int solve(string s, int i , int j) | ||
{ | ||
if(i>=j) | ||
return 0; | ||
|
||
|
||
|
||
if(palindrome(s,i,j)) | ||
return t[i][j] = 0; | ||
|
||
if(t[i][j]!=-1) | ||
return t[i][j]; | ||
|
||
int temp,ans=INT_MAX; | ||
int left,right; | ||
for(int k = i;k<=j-1;k++) | ||
{ | ||
if(t[i][k]!=-1) | ||
{ | ||
left = t[i][k]; | ||
} | ||
else | ||
{ | ||
left = solve(s,i,k); | ||
} | ||
if(t[k+1][j]!=-1) | ||
{ | ||
right = t[k+1][j]; | ||
} | ||
else | ||
{ | ||
right = solve(s,k+1,j); | ||
} | ||
|
||
temp = 1+left+right; | ||
ans = min(temp,ans); | ||
} | ||
return t[i][j] = ans; | ||
|
||
|
||
} | ||
int palindromicPartition(string str) | ||
{ | ||
// code here | ||
memset(t,-1,sizeof(t)); | ||
int n = str.length(); | ||
return solve(str,0,n-1); | ||
} | ||
}; | ||
|
||
//{ Driver Code Starts. | ||
|
||
int main(){ | ||
int t; | ||
cin>>t; | ||
while(t--){ | ||
string str; | ||
cin>>str; | ||
|
||
Solution ob; | ||
cout<<ob.palindromicPartition(str)<<"\n"; | ||
} | ||
return 0; | ||
} | ||
// } Driver Code Ends |