Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
encode-string-with-shortest-length.cpp 1.22 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-12-20 16:30 +08:00 . Create encode-string-with-shortest-length.cpp
// Time: O(n^3) on average
// Space: O(n^2)
class Solution {
public:
string encode(string s) {
vector<vector<string>> dp(s.length(), vector<string>(s.length()));
for (int len = 1; len <= s.length(); ++len) {
for (int i = 0; i + len - 1 < s.length(); ++i) {
int j = i + len - 1;
dp[i][j] = s.substr(i, len);
for (int k = i; k < j; ++k) {
if (dp[i][k].length() + dp[k + 1][j].length() < dp[i][j].length()) {
dp[i][j] = dp[i][k] + dp[k + 1][j];
}
}
string encoded_string = encode_substr(dp, s, i, j);
if (encoded_string.length() < dp[i][j].length()) {
dp[i][j] = encoded_string;
}
}
}
return dp[0][s.length() - 1];
}
private:
string encode_substr(const vector<vector<string>>& dp, const string& s, int i, int j) {
string temp = s.substr(i, j - i + 1);
auto pos = (temp + temp).find(temp, 1); // O(n) on average
if (pos >= temp.length()) {
return temp;
}
return to_string(temp.length() / pos) + '[' + dp[i][i + pos - 1] + ']';
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助