RainX_69

NUMBER OF OPERATIONS TO EXHAUST A STRING DELETING ONLY PALINDROMES | HARD | MUST DO

Mar 8th, 2023
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | Source Code | 0 0
  1. https://practice.geeksforgeeks.org/problems/minimum-steps-to-delete-a-string2956/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article
  2.  
  3. Given string s containing characters as integers only, the task is to delete all characters of this string in a minimum number of steps wherein one step you can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated.
  4.  
  5. Example 1:
  6.  
  7. Input: s = "2553432"
  8. Output: 2
  9. Explanation: In first step remove "55",
  10. then string becomes "23432" which is a
  11. palindrome.
  12. Example 2:
  13. Input: s = "1234"
  14. Output: 4
  15. Explanation: Remove each character in
  16. each step
  17.  
  18. ---------------------------------------------------------------------------------------------------------------------------------------
  19. class Solution{
  20.     public:
  21.     int minStepToDeleteString(string s) {
  22.         int n=s.size();
  23.         vector<vector<int>> dp(n,vector<int>(n,0));
  24.         for(int i=0;i<n;i++){
  25.             dp[i][i]=1;  // erasing a single character
  26.         }
  27.         for(int i=0;i<n-1;i++){
  28.             if(s[i]==s[i+1]){
  29.                 dp[i][i+1]=1;  // deleting the palindrome of size 2
  30.             }
  31.             else{
  32.                 dp[i][i+1]=2; // deleting two character
  33.             }
  34.         }
  35.         for(int len=3;len<=n;len++){
  36.             for(int start=0;start<=n-len;start++){
  37.                 int end=start+len-1;
  38.                 if(s[start]==s[end]){
  39.                     dp[start][end]=dp[start+1][end-1];
  40.                 }
  41.                 else{
  42.                     dp[start][end]=1+min(dp[start][end-1],dp[start+1][end]);
  43.                 }
  44.                 for(int par=start;par<end;par++){ // break it in two parts
  45.                     dp[start][end]=min(dp[start][end],dp[start][par]+dp[par+1][end]);
  46.                 }
  47.             }
  48.         }
  49.         return dp[0][n-1];
  50.     }
  51. };
  52.  
  53. CAN YOU FIGURE OUT A RECURSIVE SOLUTION, MR. BABOON?
Advertisement
Add Comment
Please, Sign In to add comment