LeetCode - Text Justification 题解

来源:互联网 发布:软件项目计划书 编辑:程序博客网 时间:2024/05/21 15:05

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactlyL characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words["This", "is", "an", "example", "of", "text", "justification."]
L16.

Return the formatted lines as:

[   "This    is    an",   "example  of text",   "justification.  "]

Note: Each word is guaranteed not to exceed L in length.

Corner Cases:

  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.


分析:

注意特殊处理每行只有一个和最后的一行的情况。




class Solution {public:    vector<string> ans;    vector<string> fullJustify(vector<string> &words, int L) {        int i = 0;        while(i < words.size()){            int now = words[i].length(), j = i + 1;            while(j < words.size() && now + words[j].length() + 1 <= L){                now += words[j].length() + 1;                j++;            }            string row;            int num = j - i;            now = now - num + 1;            int left = L - now;            if(num == 1){                row = words[i];                for(int k = 0; k < left; k++)                    row += " ";            }else if(j == words.size()){                left -= num - 1;                for(int k = i; k < j - 1; k++){                    row += words[k];                    row += " ";                }                row += words[j - 1];                for(int k = 0; k < left; k++)                    row += " ";            }else{                int c = left / (num - 1);                int r = left - c * (num - 1);                for(int k = i; k < i + r; k++){                    row += words[k];                    for(int o = 1; o <= c + 1; o++)                        row += " ";                }                for(int k = i + r; k < j - 1; k++){                    row += words[k];                    for(int o =1; o <=c; o++)                        row += " ";                }                row += words[j - 1];            }            i = j;            ans.push_back(row);        }        if(ans.size() > 0){            string last = ans[ans.size() - 1];        }        return ans;    }};


0 0
原创粉丝点击