68. 文本左右对齐

68. 文本左右对齐

给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

说明:

  • 单词是指由非空格字符组成的字符序列。
  • 每个单词的长度大于 0,小于等于 maxWidth
  • 输入单词数组 words 至少包含一个单词。
  • class Solution {
    public:
        string fun(int a,int b,vector<string>& c,int Max)
        {
            string s="";
            int len=0;
            for(int i=a;i<=b;i++)
            {
                len+=c[i].size();
            }
            if(a==b)
            {
                s.append(c[a]);
                s.append(Max-(int)c[a].size(),' ');
                return s;
            }
            int num=(Max-len)/(b-a);
            int num1=(Max-len)%(b-a);
            if(b==c.size()-1)
            {
                num=1;
                num1=0;
            }
            for(int i=a;i<a+num1;i++)
            {
                s.append(c[i]);
                s.append(num+1,' ');
            }
            for(int i=a+num1;i<b;i++)
            {
                s.append(c[i]);
                s.append(num,' ');
            }
            s.append(c[b]);
            int ss=Max-b+a-(int)len;
            if(b==c.size()-1)
                s.append(ss,' ');
            return s;
        }
        vector<string> fullJustify(vector<string>& words, int maxWidth) 
        {
            vector<string> res;
            int p=0,start=0;
            int count=words[p].size();
            while(p<words.size())
            {
                count=words[p].size();
                //cout<<count<<endl;
                    while(count<=maxWidth)
                {
                    if((p+1<words.size())&&count+1+words[p+1].size()<=maxWidth)
                    {
                        //cout<<p<<endl;
                        count=count+1+words[p+1].size();
                        p++;
                    }
                    else
                    {
                        string s=fun(start,p,words,maxWidth);
                        res.push_back(s);
                        //cout<<p<<endl;
                        start=p+1;
                        p=p+1;
                        break;
                    }
                }
            }
            return res;
    
        }
    };

猜你喜欢

转载自blog.csdn.net/cx1165597739/article/details/88995579
今日推荐