本文主要是介绍[leetcode刷题系列]Text Justification,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- - 模拟题, 不过写的时候要仔细, 而且要理解好题意, 其实不难。 不过我写的时候因为没理解好题意,一开始写错了- -,
每行的单词之间至少要有一个空格的。这点特别注意, 其他就没啥了
class Solution {string getString(vector<string> &words, int st, int en, int L){// specialif(st == en){string ret = words[st];int x = L - ret.size();if(x > 0)ret += string(x, ' ');return ret;}int sum = 0;for(int i = st; i <= en; ++ i)sum += words[i].size();L -= sum;int divisor = en - st;int md = L % divisor;int an = L / divisor;string ret = words[st];for(int i = st + 1; i <= en; ++ i){ret += string(an, ' ');if(md){ret += ' ';md --;}ret += words[i];}return ret;}string getString2(vector<string> &words, int st, int en, int L){string ret =words[st];for(int i = st + 1; i <= en; ++ i)ret += ' ' + words[i];if(L - ret.size() > 0)ret += string(L - ret.size(), ' ');return ret;}
public:vector<string> fullJustify(vector<string> &words, int L) {// Start typing your C/C++ solution below// DO NOT write int main() functionvector<string> ret;int last = -1;int sum = 0;for(int i = last + 1; i < words.size(); ++ i){if(sum + words[i].size() > L){ret.push_back(getString(words, last + 1, i - 1, L));sum = words[i].size() + 1;last = i - 1;}else{sum += words[i].size() + 1;}}ret.push_back(getString2(words, last + 1, words.size() - 1, L));return ret;}
};
这篇关于[leetcode刷题系列]Text Justification的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!