[LeetCode] Split Message Based on Limit

2468. Split Message Based on Limit

You are given a string, message, and a positive integer, limit.

You must split message into one or more parts based on limit. Each resulting part should have the suffix ““, where “b” is to be replaced with the total number of parts and “a” is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.

The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.

Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.

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
40
41
42
43
44
45
46
47
48
49
class Solution {
long long lg10(long long n) {
return to_string(n).length();
}
long long sublen(long long n) {
long long res = 0;
long long p = 1, l = 1;
while(p <= n) {
long long nxt = min(n, p * 10 - 1);
res += (nxt - p + 1) * l;
p *= 10;
l += 1;
}
return res;
}
vector<string> helper(string message, int limit, int p) {
if(3 + 2 * lg10(p) >= limit) return {};
vector<string> res;
string now = "";
for(int i = 0; i < message.length(); i++) {
now.push_back(message[i]);
int len = now.length() + 3 + lg10(p) + lg10(res.size() + 1);
if(len == limit) {
now += "<" + to_string(res.size() + 1) + "/" + to_string(p) + ">";
res.push_back(now);
now = "";
}
}
if(now.length()) {
now += "<" + to_string(res.size() + 1) + "/" + to_string(p) + ">";
res.push_back(now);
}
if(res.size() != p) return {};
return res;
}
public:
vector<string> splitMessage(string message, int limit) {
for(int i = message.length() / limit; i <= message.length(); i++) {
int len = i * 3 + lg10(i) * i + sublen(i) + message.length();
int target = (len + limit - 1) / limit;

if(target == i) {
auto res = helper(message,limit,i);
if(res.size()) return res;
}
}
return {};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/13/PS/LeetCode/split-message-based-on-limit/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.