Advertisement
nikunjsoni

471

Jun 21st, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. class Solution {
  2. private:
  3.     vector<vector<string>> dp;
  4. public:
  5.     string collapse(string& s, int i, int j) {
  6.         string temp = s.substr(i, j - i + 1);
  7.         auto pos = (temp+temp).find(temp, 1);
  8.         // Check if there is no suffix that is also a prefix.
  9.         if (pos >= temp.size()) {
  10.             return temp;
  11.         }
  12.         // If there exists a suffix that is also a prefix.
  13.         return to_string(temp.size()/pos) + '['+ dp[i][i+pos-1]+']';
  14.     }
  15.  
  16.     string encode(string s) {
  17.         int n = s.size();
  18.         dp = vector<vector<string>>(n, vector<string>(n, ""));
  19.         for (int step = 1; step <= n; step++) {
  20.             for (int i = 0; i + step - 1 < n; i++) {
  21.                 int j = i + step - 1;
  22.                 // There is no optimization.
  23.                 dp[i][j] = s.substr(i, step);
  24.                 for (int k = i; k < j; k++) {
  25.                     auto left = dp[i][k];
  26.                     auto right = dp[k + 1][j];
  27.                     // If it is combination of 2 optimization.
  28.                     if (left.size() + right.size() < dp[i][j].size()) {
  29.                         dp[i][j] = left + right;
  30.                     }
  31.                 }
  32.                 // If the string itself can be optimized.
  33.                 string replace = collapse(s, i, j);
  34.                 if (replace.size() < dp[i][j].size()) {
  35.                     dp[i][j] = replace;
  36.                 }
  37.             }
  38.         }
  39.         return dp[0][n - 1];
  40.     }
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement