Java - One loop (no nesting), no calculation, and hope this is more readable


  • 0
    J
    public class Solution {
    
    public List<String> fullJustify(String[] words, int maxWidth) {
    	List<String> ans = new ArrayList<>();
    	List<String> curLine = new ArrayList<String>();
    	int curLen = 0;
    
    	if (words.length == 0)
    		return ans;
    	if (words.length == 1) { // one word, tail blank.
    		curLine.add(words[0]);
    		curLen = words[0].length();
    		spacingLine(curLine, curLen, maxWidth);
    		ans.add(buildLine(curLine));
    		return ans;
    	}
    	
    	boolean lineComplete = false;
    	for (String word : words) {
    		boolean leadSpace = (curLine.size() > 0) ? true : false;
    		if (leadSpace) {
    			if (leadSpace && curLen + word.length() + 1 <= maxWidth) {
    				curLine.add(" " + word);
    				curLen += word.length() + 1;
    			} else {
    				lineComplete = true;
    			}
    		} else {
    			if (curLen + word.length() <= maxWidth) {
    				curLine.add(word);
    				curLen += word.length();
    			} else {
    				lineComplete = true;
    			}
    		}
    		if (lineComplete) {
    			//current line is complete, output the line and reset.
    			spacingLine(curLine, curLen, maxWidth);
    			ans.add(buildLine(curLine));
    			curLen = 0;
    			curLine.clear();
    			lineComplete = false;
    			
    			curLine.add(word);  //put back the remaining word.
    			curLen += word.length();
    		}
    	}
    	if (!curLine.isEmpty()) { //handle the last line, tail the blanks.
    		String lastLine = buildLine(curLine);
    		curLine.clear();
    		curLine.add(lastLine);
    		spacingLine(curLine, lastLine.length(), maxWidth);
    		ans.add(buildLine(curLine));
    	}
    	return ans;
    }
    
    //build the sting ouput for a line.
    private String buildLine(List<String> curLine) {
    	String s = "";
    	for (int i = 0; i < curLine.size(); i++) 
    		s += curLine.get(i);
    	return s;
    }
    
    //Justify a line.
    private void spacingLine(List<String> curLine, int curLen, int maxWidth) {
    	int n = maxWidth - curLen; //number of extra spaces.
    	if (curLine.size() == 1) {
    		while (n-- > 0)
    			curLine.set(0, curLine.get(0) + " ");
    	} else {
    		int i = 1;
    		while (n-- > 0 && i < curLine.size()) {
    			curLine.set(i, " " + curLine.get(i));
    			if (i == curLine.size() - 1) {
    				i = 1; //reset.
    			} else {
    				i++;
    			}
    		}
    	}
    } }

Log in to reply
 

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