Clear Java Solution


  • 0
    B
    public class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> result = new ArrayList<String>();
            if(words == null || words.length == 0 || maxWidth <= 0) {
                if(maxWidth == 0) result.add("");
                return result;
            }
            
            ArrayList<String> line = new ArrayList<String>();
            int restLen = maxWidth;
            for(int i = 0; i < words.length; i++) {
                // fill up one line
                if(words[i].length() <= restLen) {
                    line.add(words[i]);
                    restLen = restLen - words[i].length() - 1;
                    continue;
                }
                generateLine(result, line, restLen);
                // reset
                line = new ArrayList<String>();
                restLen = maxWidth;
                i--;
            }
            // left justify for last line
            leftJustify(result, line, restLen);
            return result;
        }
        
        private void generateLine(List<String> result, List<String> line, int restLen) {
            // only one word
            if(line.size() == 1) {
                leftJustify(result, line, restLen);
                return;
            }
            
            // multiple words - full justify
            StringBuilder sb = new StringBuilder();
            int spaces = restLen + line.size(); // every word deleted a space, totally re-generate
            int len = line.size() - 1;
            
            for(int i = 0; i < len && spaces > 0; spaces--) {
                line.set(i, line.get(i) + " ");
                i = (i + 1) % len;
            }
            for(String word: line) {
                sb.append(word);
            }
            result.add(sb.toString());
        }
        
        //left justify
        private void leftJustify(List<String> result, List<String> line, int restLen) {
            StringBuilder sb = new StringBuilder();
            int spaces = restLen + 1;
            for(int i = 0; i < line.size() - 1; i++) {
                sb.append(line.get(i));
                sb.append(" ");
            }
            sb.append(line.get(line.size() - 1));
            while(spaces > 0) {
                sb.append(" ");
                spaces--;
            }
            result.add(sb.toString());
        }
    }
    

Log in to reply
 

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