leetcode-----68. 文本左右对齐

代码

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ans;
        for (int i = 0; i < words.size(); ++i) {
            int j = i + 1; 
            int len = words[i].size();
            while (j < words.size() && len + 1 + words[j].size() <= maxWidth) len += 1 + words[j++].size();
            string line;
            if (j == words.size() || j == i + 1) {
                line += words[i];
                for (int k = i + 1; k < j; ++k) line += ' ' + words[k];
                while (line.size() < maxWidth) line += ' '; 
            } else {
                int cnt = j - i - 1, r = maxWidth - len + cnt;
                line += words[i];
                int k = 0;
                while (k < r % cnt) line += string(r / cnt + 1, ' ') + words[i + k + 1], k++;
                while (k < cnt) line += string(r / cnt, ' ') + words[i + k + 1], k++;
            }
            ans.push_back(line);
            i = j - 1;
        }
        return ans;
    }
};
上一篇:别让几千的工资拴你一辈子,最强的68道软件测试基础题,你若能倒背如流,工资不涨我服你!


下一篇:剑指 Offer 68 - I. 二叉搜索树的最近公共祖先(迭代,递归)2