Java solution


  • 0
    J

    there's lot of corner cases.

        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> result = new ArrayList<>();
            if (words.length == 0) return result;
            int lineLen = words[0].length(), nextStart = 0;
            for (int i = 1; i < words.length; i++) {
                if (lineLen + 1 + words[i].length() <= maxWidth) lineLen += 1 + words[i].length();
                else {
                    StringBuilder sb = new StringBuilder(words[nextStart]);
                    int leftSpace = maxWidth - lineLen;
                    int spaceCnt = i - nextStart - 1;
                    int average = spaceCnt == 0 ? leftSpace : leftSpace / spaceCnt;
                    int left = spaceCnt == 0 ? 0 : leftSpace % spaceCnt;
                    StringBuilder spaces = new StringBuilder();
                    for (int k = 0; k < average; k++) spaces.append(' ');
                    int j = nextStart + 1;
                    for (; j <= nextStart + left; j++) sb.append(spaces).append("  ").append(words[j]);
                    for (; j <= nextStart + spaceCnt; j++) sb.append(spaces).append(' ').append(words[j]);
                    for (; j < i; j++) sb.append(' ').append(words[j]);
                    if (spaceCnt == 0) sb.append(spaces);
                    result.add(sb.toString());
                    lineLen = words[i].length();
                    nextStart = i;
                }
            }
            if (nextStart < words.length) {
                StringBuilder sb = new StringBuilder();
                sb.append(words[nextStart]);
                for (int i = nextStart + 1; i < words.length; i++) sb.append(' ').append(words[i]);
                for (int i = sb.length(); i < maxWidth; i++) sb.append(' ');
                result.add(sb.toString());
            }
            return result;
        }
    

Log in to reply
 

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