[LeetCode] Encode String with Shortest Length

471. Encode String with Shortest Length

Given a string s, 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. k should be a positive integer.

If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return any of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
unordered_map<string, string> dp;
int repCount(string& s, int st, string& rep) {
int res = 1;

for(int i = st + rep.length(); i + rep.length() <= s.length(); i += rep.length()) {

for(int j = i; j < i + rep.length(); j++) {
if(rep[j-i] != s[j]) return res;
}
res++;
}
return res;
}
string solution(string s) {
if(s.length() < 5) return s;
if(dp.count(s)) return dp[s];
string res = s;
string rep = "";

for(int i = 0; i < s.length(); i++) {
rep += s[i];
int cnt = repCount(s,0,rep);
string str;

for(int j = 1; j <= cnt; j++) {
if(j == 1) str = rep + solution(s.substr(j*(i+1)));
else str = to_string(j) + '[' + solution(rep) + ']' + solution(s.substr((i+1)*j));
if(str.length() < res.length()) res = str;
}
}

return dp[s] = res;
}
public:
string encode(string s) {
return solution(s);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/encode-string-with-shortest-length/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.