Contents

68. Text Justification

Contents

https://leetcode.com/problems/text-justification/

https://leetcode.com/problems/text-justification/submissions/1030637814/

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> ans;
        for(int i = 0; i < words.size(); ){
            string tans = "";
            int j = i;
            while(j != words.size() && tans.size() + words[j].size() <= maxWidth) {
                tans += words[j];
                if(tans.size() != maxWidth) tans += " ";
                j++;
            }
            if(j == words.size()) {
                ans.push_back(tans + string(maxWidth - tans.size(), ' '));
            } else {
                ans.push_back(rerrange(tans, maxWidth));
            }
            i = j;
        }
        return ans;
    }

    inline string rerrange(string s, int maxWidth) {
        int space = 0;
        vector<string> split;
        string ts = "";
        for(auto c : s) {
            if(c == ' ') space++, split.push_back(ts), ts = "";
            else ts += c;
        }
        if(ts != "") split.push_back(ts);
        if(split.size() == 1) {
            return s + string(maxWidth - s.size(), ' ');
        }
        int extraSpace = maxWidth - s.size() + space;
        int mod = extraSpace % (split.size() - 1);
        int dev = extraSpace / (split.size() - 1);
        s = "";
        for(int i = 0; i < split.size() - 1; ++i) {
            s += split[i];
            if(mod != 0) s += string(dev + 1, ' '), mod--;
            else s += string(dev, ' ');
        }
        s += split.back();
        return s;
    }
};