LC68-文本左右对齐
68. 文本左右对齐
贪心 + 模拟
将单词存入数组后调整单词之间的距离。
class Solution {
public:
string adjust1(vector<string>& t, int maxWidth){//非最后一行调整
string res = "";
if(t.size() == 1){
res = t[0];
while(res.size() != maxWidth)res.push_back(' ');
}
else {
int tot = 0;
for(int i = 0; i < t.size(); ++i)tot += t[i].size();
int diff = maxWidth - tot,n = t.size() - 1;
int a = diff / n;
int b = a * n;
int c = diff - b;
for(int i = 0; i < c; ++i){
res += t[i];
for(int k = 0; k < a + 1; ++k)res += ' ';
}
for(int i = c; i < t.size(); ++i){
res += t[i];
for(int k = 0; k < a; ++k)res += ' ';
}
while(res.size() != maxWidth)res.pop_back();
}
return res;
}
string adjust2(vector<string>&t, int maxWidth){//最后一行调整
string res = "";
for(int i = 0; i < t.size(); ++i)res += t[i],res += ' ';
if(res.size() > maxWidth)res.pop_back();
while(res.size() != maxWidth)res.push_back(' ');
return res;
}
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string>res, t;
for(int i = 0; i < words.size(); ++i){
int j = i, len = 0;t.clear();
t.push_back(words[j ++]), len += t[0].size();
while(j < words.size() && len + 1 + words[j].size() <= maxWidth)
t.push_back(words[j]), len += 1 + words[j ++].size();
string cur = "";
if(j >= words.size())cur = adjust2(t,maxWidth);
else cur = adjust1(t,maxWidth);
res.push_back(cur);
i = j - 1;
}
return res;
}
};
浙公网安备 33010602011771号