Advertisement
knakul853

Untitled

Jul 26th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int minCut(string s) {
  4.        
  5.         int n = (int)s.size();
  6.         vector<vector<bool>>palin(n+1, vector<bool>(n+1,false));
  7.        
  8.         //palin(i, j) the substring i...j is palindrome or not.
  9.         vector<int>dp(n+1, 0); // minimum cut for the 0...ith char.
  10.        
  11.         for(int i=0;i<=n;i++) {dp[i] = i-1;}
  12.        
  13.         for(int i=2;i<=n;i++){
  14.             for(int j=i-1;j>=0;j--){
  15.                
  16.                 if(s[i-1] == s[j]  && (i-1-j<2 || palin[j+1][i-1])){
  17.                     palin[j][i] = true;
  18.                    
  19.                     dp[i] = min(dp[i], dp[j]+1);
  20.                 }
  21.             }
  22.         }
  23.        
  24.      
  25.        
  26.         return dp[n];
  27.        
  28.     }
  29.    
  30.  
  31. };
  32.  
  33. // space can be optimized, just use the even, odd palindrome concept.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement