https://leetcode.com/problems/text-justification/
---------------------------------------------------
A trivial string problem. Logic is not difficult, but it takes time to correctly code the problem.
1. fetch enough words;
2. compose the line: there are three kinds of line, namely
one word line;
last line;
the other lines.
/////////////////////////////////////////////////////////
// codes
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
int len = words.size();
//check
input
if (maxWidth == 0)return{ "" };
//top
loop
for (int i = 0; i<words.size(); ){
int j = 0, wLen = 0, sLen = 0;
while (i + j<len){
wLen += words[i + j].size();
if (j + 1 >= 2)sLen = j + 1
- 2 + 1;//space
if (wLen + sLen>maxWidth){
wLen -= words[i + j].size();
j--;
break;
}
else if (i + j == len - 1)break;
j++;
}
string tmp;
//compose the line
//only one word
if (j == 0){
tmp = words[i + j];
tmp.resize(maxWidth, ' ');
res.push_back(tmp);
}
//last line
else if (i + j == words.size()-1){
for (int k = i; k<i + j + 1; k++){
tmp.append(words[k]);
tmp.push_back(' ');
}
tmp.resize(maxWidth, ' ');
res.push_back(tmp);
}
//others
else{
sLen = maxWidth - wLen;
int sMod = sLen%j, sDiv = sLen /
j;
int count = sMod;
for (int k = i; k<i+j + 1; k++){
tmp.append(words[k]);
//more space appended
if (count!=0){
string space(1 + sDiv, ' ');
tmp.append(space);
count--;
}
//less space appended
else{
string space(sDiv, ' ');
tmp.append(space);
}
}
tmp.resize(maxWidth);//remove the last extra spaces
res.push_back(tmp);
}
i = i + j + 1;
}
return res;
}
};
No comments:
Post a Comment