My 0ms Solution in c++


  • 0
    G
    class Solution {
    public:
    	vector<string> fullJustify(vector<string>& words, int maxWidth) {
    		vector<string> text;
    		int n = words.size();
    
    		if (n > 0) {
    			int i = 0;
    			int j = 0;
    
    			while (j < n) {
    				int currSize = -1;
    				while (j < n && (currSize + words[j].length() + 1) <= maxWidth) {
    					currSize += (words[j].length() + 1);
    					j++;
    				}
    
    				if (currSize < 0) {
    					break;
    				}
    
    				int currLineWords = j - i;
    				int spacesAvail = maxWidth - currSize + currLineWords - 1;
    				int gaps = currLineWords - 1;
    
    				if (gaps > 0) {
    					vector<int> spaceGaps(gaps, 0);
    					int rem = 0;
    					int rest = 0;
    
                        if (gaps == 1 && j == n) {
                            rem = 0;
                        } else if (gaps == 1 && j < n) {
    						rem = spacesAvail;
    					} else if (spacesAvail % gaps != 0) {
    						rem = spacesAvail % gaps;
    					}
    
    					spacesAvail -= rem;
    					rest = spacesAvail / gaps;
    
    					if (j == n) {
    						for (int k = 0; k < gaps; k++) {
    							spaceGaps[k] = 1;
    						}
    					} else {
    						for (int k = 0; k < gaps; k++) {
    							spaceGaps[k] = rest;
    						}
    
    						for (int k = 0; k < rem; k++) {
    							spaceGaps[k % gaps]++;
    						}
    					}
    
    					string temp;
    					temp += words[i++];
    
    					for (int k = 0; k < gaps; k++) {
    						temp += string(spaceGaps[k], ' ');
    						temp += words[i++];
    					}
    
    					if (j == n && maxWidth - temp.length() > 0) {
    						temp += string(maxWidth - temp.length(), ' ');
    					}
    
    					text.push_back(temp);
    				} else {
    					string temp = words[i];
    					if (words[i].size() < maxWidth) {
    						temp += string(maxWidth - words[i].length(), ' ');
    					}
    
    					i++;
    					text.push_back(temp);
    				}
    			}
    		}
    
    		return text;
    	}
    };

Log in to reply
 

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