[LeetCode]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 Lcharacters.

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.

click to show corner cases.

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> fullJustify(vector<string> &words, int L) {
        vector<string> res;
        string ans="";
		int len=0,i,j;
		int size1=words.size(); //words大小
		if(words[0]=="") //空字符串返回L个空格
		{
		    ans.insert(0,L,' ');
		    res.push_back(ans);
            return res;
		}
        //插入字符串
       for(i=0;i<size1;i++)
        {
            if(ans=="") //单词大小<L
			{
				if(len+words[i].size()<=L)
				{
					len+=words[i].size();
					ans+=words[i];
				}
			}
			else
			{
				if(len+words[i].size()<L)
				{
					len+=1+words[i].size();
					ans+=' '+words[i];
				}
				else
				{
					res.push_back(ans);
					ans="";
					len=0;
					i--;
				}
			}
		    if(i==size1-1) 
			{
				res.push_back(ans);
				break;
			}
        }
		int size2=res.size();
        //调整格式
        //for(i=0;i<size2;i++)
		//	cout<<res[i]<<endl;
        for(i=0;i<size2-1;i++)
		{
			len=res[i].size();
			int count=L-len; //添加空格数
			int num=0; //字符串间隔数
			for(j=0;j<res[i].size();j++)
			{
				if(res[i][j]==' ') num++;
			}
		    if(num==0) res[i].insert(res[i].size(),L-len,' '); //只有一个单词,全部加在末尾
			else
			{
				int k1=count/num; //每个间隔增加几个空格
			    int k2=count%num; //多余的空格
				j=0;
				while(j<res[i].size()) //res[i].size()动态增加
				{
					if(res[i][j]==' ') //添加空格
					{
						if(k2>0) //看是否要多加一个空格
						{
							res[i].insert(j,k1+1,' ');
							j+=k1+1;
							k2--;
						}
						else
						{
							res[i].insert(j,k1,' ');
							j+=k1;
						}
					}
					j++;
				}
			}
		}
		//最后一行单独处理
		len=res[size2-1].size();
		res[size2-1].insert(len,L-len,' ');
		return res;
    }
};

  

 

posted @ 2014-01-12 21:38  七年之后  阅读(377)  评论(0编辑  收藏  举报