Share my c++ solution


  • 0
    A
    class Solution {
    public:
        vector<string> fullJustify(vector<string>& words, int maxWidth) {
            int len = words.size();
        	int idx = 0;
        	vector<string> ret;
        	while(idx < len)
        	{
        		int width = 0;
        		vector<string> line;
        		while(idx < len && width+words[idx].length()<= maxWidth)
        		{
        			line.push_back(words[idx]);
        			width += words[idx].length();
        			width++;   // space
        			idx++;
        		}
        		string sentence = line[0];
        		
        		if( idx == len)
        		{
        			for(int i = 1; i < line.size(); i++)
        				sentence += " " + line[i];
        		}
        		else if( line.size() > 1)
        		{
        			int wordsWidth = 0;
        			for(int i = 0; i < line.size(); i++)
        				wordsWidth += line[i].length();
        			int numSpace = (maxWidth - wordsWidth) / (line.size()-1);
        			int kth = maxWidth - wordsWidth - numSpace*(line.size()-1);
        			for(int i = 1; i < line.size(); i++)
        			{
        				if( i <= kth)
        					sentence += " ";
        				sentence += string(numSpace, ' ') + line[i];
        			}	
        		}
        		if(sentence.length() < maxWidth)
        			sentence += string(maxWidth-sentence.length(), ' ');
        		ret.push_back(sentence);
        	}
        	return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.