Given a non-empty string, encode the string such that its encoded length is the shortest.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.
Note:
1、k will be a positive integer and encoded string will not be empty or have extra space.
2、You may assume that the input string contains only lowercase English letters. The string’s length is at most 160.
3、If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return any of them is fine.
示例
示例 1:
输入:"aaa"
输出:"aaa"
解释:无法将其编码为更短的字符串,因此不进行编码。
示例 2:
输入:"aaaaa"
输出:"5[a]"
解释:"5[a]" 比 "aaaaa" 短 1 个字符。
示例 3:
输入:"aaaaaaaaaa"
输出:"10[a]"
解释:"a9[a]" 或 "9[a]a" 都是合法的编码,和 "10[a]" 一样长度都为 5。
示例 4:
输入:"aabcaabcd"
输出:"2[aabc]d"
解释:"aabc" 出现两次,因此一种答案可以是 "2[aabc]d"。
示例 5:
输入:"abbbabbbcabbbabbbc"
输出:"2[2[abbb]c]"
解释:"abbbabbbc" 出现两次,但是 "abbbabbbc" 可以编码为 "2[abbb]c",因此一种答案可以是 "2[2
解题
class Solution {
public:
string encode(string s) {
int n = s.size();
vector<vector<string>> dp(n, vector<string>(n, ""));
for (int step = 1; step <= n; ++step) {
for (int i = 0; i + step - 1 < n; ++i) {
int j = i + step - 1;
dp[i][j] = s.substr(i, step);
for (int k = i; k < j; ++k) {
string left = dp[i][k], right = dp[k + 1][j];
if (left.size() + right.size() < dp[i][j].size()) {
dp[i][j] = left + right;
}
}
string t = s.substr(i, j - i + 1), replace = "";
auto pos = (t + t).find(t, 1);
if (pos >= t.size()) replace = t;
else replace = to_string(t.size() / pos) + '[' + dp[i][i + pos - 1] + ']';
if (replace.size() < dp[i][j].size()) dp[i][j] = replace;
}
}
return dp[0][n - 1];
}
};
LeetCode刷题实战462:最少移动次数使数组元素相等 II
LeetCode刷题实战470:用 Rand7() 实现 Rand10()
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/17241.html