string addSpaces(int cnt){
return std::string(cnt, ' '); // char
}
// Greedily try to go as far right as possible until we fill our current line
pair<int,int> findRight(vector<string>& words, int maxWidth, int l){
int wLen = words[l].size(); // sum of lengths of words from l to r. + default whitespaces
int n = words.size(), r = l+1;
while(r < n && wLen + 1+words[r].size() <= maxWidth){
wLen += 1+words[r].size(); // +1 for default whitespace
r++;
}
return {r-1, wLen};
}
string makeLine( vector<string>& words, int maxWidth, int l, int r, int wLen){
int n = words.size(), spaces = maxWidth-wLen; // EXTRA whitespaces needed
if(l == r) return words[l] + addSpaces(spaces);
string line = "";
bool isLast = (r == n-1);
// Split EXTRA spaces. In between r-l+1 words, there are r-l spaces
auto [q, rem] = std::div(spaces, r-l);
for(int i=l; i< r; i++){
line += words[i];
line += " ";
if(!isLast){
line += addSpaces(q);
if(rem > 0) line += " "; // evenly distribute remaining spaces
rem--;
}
}
line += words[r];
if(isLast) line += addSpaces(spaces); // left justify
return line;
}
vector<string> Solution::fullJustify( vector<string>& words, int maxWidth) {
int n = words.size(), l=0, r=0;
vector<string> ans;
while(l < n){
auto [r, wLen] = findRight( words, maxWidth, l);
string line = makeLine( words, maxWidth, l, r, wLen);
ans.push_back( line);
l = r+1;
}
return ans;
}
댓글 영역
획득법
① NFT 발행
작성한 게시물을 NFT로 발행하면 일주일 동안 사용할 수 있습니다. (최초 1회)
② NFT 구매
다른 이용자의 NFT를 구매하면 한 달 동안 사용할 수 있습니다. (구매 시마다 갱신)
사용법
디시콘에서지갑연결시 바로 사용 가능합니다.