Edge cases

68. Text Justification

Jimmy (xiaoke) Shen
1 min readAug 12, 2020
class Solution {
public:
string get_sentense(vector<string>& words, int i, int j, int len, int maxWidth, string align="justified")
{
string ret = "";
if (align == "justified")
{
if (j == i)
{
ret = words[i];
int k = ret.length();
for (; k < maxWidth; ++k) ret += " ";
return ret;
}

int space = (maxWidth - len) / (j - i);
int extra_space = (maxWidth - len) % (j - i);
for (int k = 0; i + k <= j; ++k)
{
ret += words[i+k];
if (k < extra_space)
{
for (int spc = 0; spc < space+1; ++spc)
ret += " ";
}
else if (i+k != j)
{
for (int spc = 0; spc < space; ++spc)
ret += " ";
}
}
}
else
{
for (int k = 0; i + k <= j; ++k)
{
ret += words[i+k];
if(i + k != j)ret += " ";
}
int k = ret.length();
for (; k < maxWidth; ++k) ret += " ";
}
return ret;
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ret;
int i = 0, ii = 0;
int j = 0;
while (ii <= words.size())
{
if (ii == words.size())
{
auto this_ret = get_sentense(words, i, ii-1, j, maxWidth, "left");
ret.push_back(this_ret);
break;
}
j += words[ii].length();
if (j + (ii - i) > maxWidth)
{
auto this_ret = get_sentense(words, i, ii-1, j-words[ii].length(), maxWidth);
ret.push_back(this_ret);
j = 0;
i = ii;
}
else
ii++;
}
return ret;
}
};

--

--

No responses yet