forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit-message-based-on-limit.cpp
More file actions
31 lines (30 loc) · 965 Bytes
/
split-message-based-on-limit.cpp
File metadata and controls
31 lines (30 loc) · 965 Bytes
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
// Time: O(n + rlogr), r is the number of messages
// Space: O(1)
// brute force, linear search (binary search doesn't work)
class Solution {
public:
vector<string> splitMessage(string message, int limit) {
int cnt = 1, l = 1;
for (int total = size(message) + 1, base = 1; 3 + l * 2 < limit;) {
if (total + (3 + l) * cnt <= limit * cnt) {
break;
}
++cnt;
if (cnt == 10 * base) {
++l;
base *= 10;
}
total += l;
}
if (3 + l * 2 >= limit) {
return {};
}
vector<string> result;
for (int i = 0, j = 0; i < cnt; ++i) {
const int l = limit - (3 + size(to_string(i + 1)) + size(to_string(cnt)));
result.emplace_back(message.substr(j, l) + '<' + to_string(i + 1) + '/' + to_string(cnt) + '>');
j += l;
}
return result;
}
};