leetcode_c++:Text Justification(068)

来源:互联网 发布:数据录入员笔试试题 编辑:程序博客网 时间:2024/06/06 14:07

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.”]
L: 16.

Return the formatted lines as:
[
“This is an”,
“example of text”,
“justification. ”
]
Note: Each word is guaranteed not to exceed L in length.


算法:

//给出单词和宽度,要求将单词打包成宽度一样的字符串数组
要求:
1. 每个字符串尽可能包含多个单词,多余的位置用空格代替
2. 单词间空格尽量的平均,不能平均的话,前面的空格要比后面的空格多


#include<iostream>#include<iostream>#include<string>#include<vector>#include<math.h>using namespace std;class Solution {private:    string getOneLine(vector<string> &words,int start,int end,int rest,int L){        string line=words[start];        rest+=(end-start);        int even_space=rest+1,num_of_more=0;        if(start!=end){            even_space=rest/(end-start);            num_of_more=rest-even_space*(end-start);        }        for(int i=start+1;i<=end;++i){            if(i-start<=num_of_more)                line.append(even_space+1,' ');            else                line.append(even_space,' ');            line+=words[i];        }        if(line.size()<L)            line.append(L-line.size(),' ');        return line;    }public:    vector<string> fullJustify(vector<string>& words, int maxWidth) {        vector<string> ret;        int sz=words.size();        int start_pos=0;        int cur_len=0;        for(int i=0;i<sz;++i){            if(cur_len+words[i].length()>maxWidth){                ret.push_back(getOneLine(words,start_pos,i-1,maxWidth-cur_len+1,maxWidth));                start_pos=i;                cur_len=0;            }            cur_len+=words[i].length();            cur_len+=1;        }        ret.push_back(getOneLine(words,start_pos,sz-1,0,maxWidth));        return ret;    }};int main(){    int n,1;    cin>>n>>1;    vector<string> w(n);    for(auto &i:w)        cin>>i;    Solution s;    vector<string> ans=s.fullJustify(w,1);    for(auto &i:ans)        cout<<i<<endl;    return 0;}
0 0
原创粉丝点击