An clear easy to understand C++ solution


  • 0
    L
    class Solution {
    public:
        vector<string> ret;
        void addLine(vector<string>& line, int maxWidth) {
            int n = line.size();
            int space = 0;
            string str;
            for (int i = 0; i < n; ++i)
                space += line[i].size();
            space = maxWidth - space;
            str = line[0];
            for (int i = 1; i < n; ++i) {
                int m = (space + (n - i - 1)) / (n - i);
                str += string(m, ' ') + line[i];
                space -= m;
            }
            str.resize(maxWidth, ' ');
            ret.push_back(str);
            line.clear();
        }
        void addLastLine(vector<string>& line, int maxWidth) {
            string str;
            for (string w : line)
                str += w + " ";
            str.resize(maxWidth, ' ');
            ret.push_back(str);
        }
        vector<string> fullJustify(vector<string>& words, int maxWidth) {
            vector<string> line;
            int width = 0;
            for (int i = 0; i < words.size(); ++i) {
                if (width + words[i].size() + (width == 0 ? 0 : 1) > maxWidth) {
                    addLine(line, maxWidth);
                    width = 0;
                }
                line.push_back(words[i]);
                width += words[i].size() + (width == 0 ? 0 : 1);
            }
            addLastLine(line, maxWidth);
            return ret;
        }
    };

  • 0
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.