?LeetCode刷題實(shí)戰(zhàn)471:編碼最短長(zhǎng)度的字符串
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"
解釋:無(wú)法將其編碼為更短的字符串,因此不進(jìn)行編碼。
示例 2:
輸入:"aaaaa"
輸出:"5[a]"
解釋:"5[a]"?比 "aaaaa"?短 1?個(gè)字符。
示例 3:
輸入:"aaaaaaaaaa"
輸出:"10[a]"
解釋:"a9[a]"?或 "9[a]a"?都是合法的編碼,和 "10[a]"?一樣長(zhǎng)度都為 5。
示例 4:
輸入:"aabcaabcd"
輸出:"2[aabc]d"
解釋:"aabc"?出現(xiàn)兩次,因此一種答案可以是 "2[aabc]d"。
示例 5:
輸入:"abbbabbbcabbbabbbc"
輸出:"2[2[abbb]c]"
解釋:"abbbabbbc"?出現(xiàn)兩次,但是 "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];
????}
};
LeetCode1-460題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)461:漢明距離
LeetCode刷題實(shí)戰(zhàn)462:最少移動(dòng)次數(shù)使數(shù)組元素相等 II
LeetCode刷題實(shí)戰(zhàn)463:島嶼的周長(zhǎng)
LeetCode刷題實(shí)戰(zhàn)464:我能贏嗎
LeetCode刷題實(shí)戰(zhàn)465:最優(yōu)賬單平衡
LeetCode刷題實(shí)戰(zhàn)466:統(tǒng)計(jì)重復(fù)個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)467:環(huán)繞字符串中唯一的子字符串
LeetCode刷題實(shí)戰(zhàn)468:驗(yàn)證IP地址
LeetCode刷題實(shí)戰(zhàn)469:凸多邊形
LeetCode刷題實(shí)戰(zhàn)470:用 Rand7() 實(shí)現(xiàn) Rand10()
