From 25521ac2491f87e24f5c84c6059265a7044adad4 Mon Sep 17 00:00:00 2001 From: Pranshu <75555961+Pranshu820@users.noreply.github.com> Date: Tue, 18 Oct 2022 15:55:01 +0530 Subject: [PATCH] Create String Compression II.cpp --- C++/String Compression II.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/String Compression II.cpp diff --git a/C++/String Compression II.cpp b/C++/String Compression II.cpp new file mode 100644 index 0000000..a8c534f --- /dev/null +++ b/C++/String Compression II.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int dp[101][101]; + int dfs(string &s, int left, int K) { + int k = K; + if(s.size() - left <= k) return 0; + if(dp[left][k] >= 0) return dp[left][k]; + int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1; + for(int i = left + 1; i <= s.size(); ++i) { + res = min(res, dfs(s, i, k) + 1 + (c >= 100 ? 3 : (c >= 10 ? 2 : (c > 1 ? 1 :0)))); + if(i == s.size()) break; + if(s[i] == s[left]) ++c; + else if(--k < 0) break; + } + return dp[left][K] = res; + } + + int getLengthOfOptimalCompression(string s, int k) { + memset(dp, -1, sizeof(dp)); + return dfs(s, 0, k); + } +};