码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Text Justification"

时间:2014-08-13 10:17:25      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   ar   art   

Just take care of corner cases!

class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> ret;

        int startInx = 0;
        while (startInx < words.size())
        {
            //    Get word count a line
            int wcnt = 0, spcnt = 0;
            int i = 0;
            bool lastRm = false;
            for (i = startInx; i < words.size(); i++)
            {
                wcnt += words[i].length();
                spcnt = i - startInx + wcnt;
                if (spcnt >= L)
                {
                    lastRm = spcnt > L;
                    break;
                }
            }

            if (!lastRm) // good luck
            {
                string line;
                for (int j = startInx; j <= i && j < words.size(); j++)
                {
                    line += words[j];
                    if (j < i) line +=  ;
                }
                if (line.length() < L)    // should only happen to last word
                {
                    line.append(L - line.length(),  );
                }
                ret.push_back(line);
            }
            else    // needs to chop last one
            {
                //    Handle spaces
                spcnt -= words[i].length() + 1;
                int slotCnt = i - startInx - 1;
                int sp2fill = L - spcnt + slotCnt;
                vector<string> sp; 
                if (slotCnt == 0) slotCnt = 1;
                sp.resize(slotCnt);
                for (int k = 0; k < sp2fill; k++)
                {
                    sp[k % slotCnt] +=  ;
                }
                //    Compose
                string line;
                for (int j = startInx; j < i; j++)
                {
                    line += words[j];
                    if (j < i - 1 || (i - startInx) == 1)
                    {
                        line += sp[j - startInx];
                    }
                }
                ret.push_back(line);
            }

            startInx = lastRm ? i : i + 1;
        }

        return ret;
    }
};

LeetCode "Text Justification",布布扣,bubuko.com

LeetCode "Text Justification"

标签:style   blog   color   os   io   for   ar   art   

原文地址:http://www.cnblogs.com/tonix/p/3909243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!