LeetCode 68 Text Justification

题意:

给出许多单词和一行能显示的最大长度,将所有单词按照两端对齐的方式进行排版,最后一行左对齐并用空格补齐长度。


思路:

一行一行的排版,每一行检查最多能放几个单词,即先假设单词之间只用1个空格分隔。

确定了一行要显示的单词数后,判断是否为最后一行,如果是,那么单词间用1个空格分隔,最后补空格到行最大长度;若不是最后一行,则每个单词后跟几个空格需要计算,计算方法见代码19和20行。


代码:

class Solution {
public:
    vector  fullJustify(vector  &words, int maxWidth) {
        vector  ans;
        for (int i = 0; i < words.size();) {
            int count = words[i].size();
            int num = 1;
            int j = i + 1;
            while (j < words.size()) {
                if (count + words[j].size() + num > maxWidth) {
                    break;
                }
                count += words[j].size();
                ++num;
                ++j;
            }
            stringstream ss;
            if (j != words.size() && num > 1) {
                int space = (maxWidth - count) / (num - 1);
                int last = (maxWidth - count) - (num - 1) * space;
                ss << words[i++];
                while (i < j) {
                    for (int k = 1; k <= space; ++k) {
                        ss << ' ';
                    }
                    if (last) {
                        --last;
                        ss << ' ';
                    }
                    ss << words[i++];
                }
                ans.push_back(ss.str());
            } else {
                ss << words[i++];
                while (i < j) {
                    ss << ' ' << words[i++];
                }
                for (int k = count + num; k <= maxWidth; ++k) {
                    ss << ' ';
                }
                ans.push_back(ss.str());
            }
        }
        return ans;
    }
};


你可能感兴趣的:(LeetCode,杂题,LeetCode,杂题)