Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created February 5, 2019 06:43
Show Gist options
  • Save kanrourou/542fcd8be5d4de25c1a70d8c2c66c60b to your computer and use it in GitHub Desktop.
Save kanrourou/542fcd8be5d4de25c1a70d8c2c66c60b to your computer and use it in GitHub Desktop.
class Solution
{
public:
vector<string> split(const string& message, int limit)
{
int len = message.size(), k = len % limit ? len / limit + 1 : len / limit, digitsOfN = to_string(k).size();
vector<string> res;
while (!canSplit(message, limit, digitsOfN, res))++digitsOfN;
return res;
}
private:
bool canSplit(const string& message, int limit, int digitsOfN, vector<string>& res)
{
//calculate length of (?/n)
int helper = digitsOfN + 3, i = 0;
//try to split with current digitsOfN
while (i < message.size())
{
int cnt = res.size() + 1, padding = to_string(cnt).size() + helper, step = limit - padding;
string str;
if (i + step >= message.size())
{
str = message.substr(i);
i += step;
}
else
{
int j = i + step;
while (message[j] != ' ')--j;
str = message.substr(i, j - i);
i = j + 1;
}
res.push_back(str);
++cnt;
}
int n = res.size();
if (to_string(n).size() == digitsOfN)
{
for (int i = 1; i <= n; ++i)
{
string info = "(" + to_string(i) + "/" + to_string(n) + ")";
res[i - 1] += info;
}
return true;
}
res.clear();
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment