Java Solution


  • 0
    M
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> list = new ArrayList<>();
            if (words == null || words.length == 0 || maxWidth < 0) return list;
            int n = words.length;
            int i = 0, j = 0;
            while (i < n && j < n) {
                int len = words[i].length();
                if (maxWidth < len) return new ArrayList<String>();
                for (j = i + 1; j < n; ++j) {
                    len += 1 + words[j].length();
                    if (len > maxWidth) break;
                }
                if (j == i + 1 || j == n) {
                    StringBuffer sb = new StringBuffer();
                    for (int k = i; k < j; ++k) {
                        if (sb.length() > 0) sb.append(" ");
                        sb.append(words[k]);
                    }
                    while (sb.length() < maxWidth) sb.append(" ");
                    list.add(sb.toString());
                } else {
                    len -= words[j].length() + 1;
                    len -= j - i - 1;
                    int lenSpaces = maxWidth - len;
                    int gapLen = lenSpaces / (j - i - 1);
                    int gapLarNum = lenSpaces % (j - i - 1);
                    StringBuffer gap = new StringBuffer();
                    for (int k = gapLen; k > 0; --k) gap.append(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int k = i; k < j; ++k) {
                        if (sb.length() > 0) {
                            sb.append(gap);
                            if (--gapLarNum >= 0) sb.append(" ");
                        }
                        sb.append(words[k]);
                    }
                    list.add(sb.toString());
                }
                i = j;
            }
            return list;
        }
    

Log in to reply
 

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