Text Justification by JAVA


  • 0
    W

    public List<String> fullJustify(String[] words, int maxWidth) {

            List<String> lines = new ArrayList<String>();		
    	for(int i = 0, k, len; i < words.length; i += k) {
            for(k =0, len = 0; i + k < words.length && len + words[i+k].length() <= maxWidth - k; k++) {
                len += words[i+k].length();
            }
            StringBuilder tmp = new StringBuilder(new String(words[i]));
            for(int j = 0; j < k - 1; j++) {
                if(i + k >= words.length) tmp.append(" ");
                else {
                	int tp = (maxWidth - len) / (k - 1) + ((j < (maxWidth - len) % (k - 1))? 1:0);
                	for (int m = 0; m < tp; m++) {
                		tmp.append(" ");
    		}
                }
                	
                tmp.append(words[i+j+1]);
            }
            int np = maxWidth - tmp.length();
            for (int n = 0; n < np; n++) {
        		tmp.append(" ");
    	}
            lines.add(tmp.toString());
        }
        return lines;
    }

Log in to reply
 

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