[leetcode] 68. Text Justification 解题报告

题目链接: https://leetcode.com/problems/text-justification/

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 exactly L 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.



思路:就是一个字符串处理的题目,并不难,但是却很难写的比较优雅.

两个代码如下,第一个是我自己的,代码比较长,0ms.第二个是参考的别人的,4ms,但是比较漂亮.

第二种方法很巧妙的求不均衡空格,就是利用位置与除余的关系来让左边分配多余空格.

代码如下:

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        int cnt = 0, left = 0;
        vector<string> result;
        for(int i =0; i< words.size(); i++)
        {
            cnt += words[i].size();
            if(cnt+i-left > maxWidth || i+1==words.size())
            {
                if(cnt+i-left > maxWidth) cnt -= words[i--].size();
                string str = words[left];
                for(int j = left+1; j<= i; j++)
                {
                    int m = maxWidth-cnt, n = i-left;
                    if(i+1==words.size()) str += " ";
                    else str.append(m/n + (j-left-1<m % n), ' ');
                    str += words[j];
                }
                str.append(maxWidth-str.size(), ' ');
                result.push_back(str);
                left = i+1, cnt = 0;
            }
        }
        return result;
    }
};



class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
        vector<string> result;
        for(int i=0, m, n; i< words.size(); i+=m)
        {
            for(m=0,n=0;i+m<words.size()&&m+n+words[i+m].size()<=maxWidth; m++) 
                n+= words[i+m].size();
            string str = words[i];
            for(int j = 0; j < m-1; j++)
            {
                if(i+m >= words.size()) str+= " ";
                else
                    str.append((maxWidth-n)/(m-1) + (j<(maxWidth-n)%(m-1)), ' ');
                str += words[i+j+1];
            }
            str.append(maxWidth-str.size(), ' ');
            result.push_back(str);
        }
        return result;
    }
};
第二种参考: https://leetcode.com/discuss/13610/share-my-concise-c-solution-less-than-20-lines




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