LeetCode OJ-- Text Justification

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

细节题

class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> ans;
        
        if(L == 0)
        {
            ans.push_back("");
            return ans;
        }
        
        int index = 0;
        int begin = 0;
        int tempLen = 0;
        int end = 0;
        int spaces = 0;
        int extraSpace = 0;
        while(index < words.size())
        {
            begin = index;
            tempLen = words[index].size();
            index++;
            while(index < words.size() && (tempLen + 1 + words[index].size()) <= L)
            {
                tempLen = tempLen + 1 + words[index].size();
                index++;
            }
            end = index - 1;
            string str;
            // not the last line
            if(end != words.size() - 1)
            {
                // has more than one word
                if(end != begin)
                {
                    spaces = (L - tempLen) / (end - begin);
                    extraSpace = (L - tempLen) % (end - begin);
                    string strSpace;
                    for(int i = 0; i < spaces + 1; i++)
                    strSpace.append(" ");
                    for(int p = begin; p < end; p++)
                    {
                        str.append(words[p]);
                        str.append(strSpace);
                        if(p - begin < extraSpace)
                            str.append(" ");
                    }
                    str.append(words[end]);
                }
                else
                {
                    str.append(words[begin]);
                    while(str.size() < L)
                        str.append(" ");
                }
            }
            else
            {
                for(int p = begin; p < end; p++)
                {
                    str.append(words[p]);
                    str.append(" ");
                }
                str.append(words[end]);
                while(str.size() < L)
                    str.append(" ");
            }
            ans.push_back(str);
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3913388.html